1. Trang chủ >
  2. Công Nghệ Thông Tin >
  3. Kỹ thuật lập trình >

Section 6.1: Exporting with ES6 syntax

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (2.79 MB, 334 trang )


Chapter 7: How modules are loaded

Section 7.1: Global Mode

If you installed Node using the default directory, while in the global mode, NPM installs packages into

/usr/local/lib/node_modules. If you type the following in the shell, NPM will search for, download, and install the



latest version of the package named sax inside the directory /usr/local/lib/node_modules/express:

$ npm install -g express



Make sure that you have sufficient access rights to the folder. These modules will be available for all node process

which will be running in that machine

In local mode installation. Npm will down load and install modules in the current working folders by creating a new

folder called node_modules for example if you are in /home/user/apps/my_app a new folder will be created called

node_modules /home/user/apps/my_app/node_modules if its not already exist



Section 7.2: Loading modules

When we refer the module in the code, node first looks up the node_module folder inside the referenced folder in

required statement If the module name is not relative and is not a core module, Node will try to find it inside the

node_modules folder in the current directory. For instance, if you do the following, Node will try to look for the file

./node_modules/myModule.js:

var myModule = require('myModule.js');



If Node fails to find the file, it will look inside the parent folder called ../node_modules/myModule.js. If it fails again,

it will try the parent folder and keep descending until it reaches the root or finds the required module.

You can also omit the .js extension if you like to, in which case node will append the .js extension and will search

for the file.

Loading a Folder Module

You can use the path for a folder to load a module like this:

var myModule = require('./myModuleDir');



If you do so, Node will search inside that folder. Node will presume this folder is a package and will try to look for a

package definition. That package definition should be a file named package.json. If that folder does not contain a

package definition file named package.json, the package entry point will assume the default value of index.js, and

Node will look, in this case, for a file under the path ./myModuleDir/index.js.

The last resort if module is not found in any of the folders is the global module installation folder.



GoalKicker.com – Node.js Notes for Professionals



59



Chapter 8: Cluster Module

Section 8.1: Hello World

This is your cluster.js:

const cluster = require('cluster');

const http = require('http');

const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {

// Fork workers.

for (let i = 0; i < numCPUs; i++) {

cluster.fork();

}

cluster.on('exit', (worker, code, signal) => {

console.log(`worker ${worker.process.pid} died`);

});

} else {

// Workers can share any TCP connection

// In this case it is an HTTP server

require('./server.js')();

}



This is your main server.js:

const http = require('http');

function startServer() {

const server = http.createServer((req, res) => {

res.writeHead(200);

res.end('Hello Http');

});

server.listen(3000);

}

if(!module.parent) {

// Start server if file is run directly

startServer();

} else {

// Export server, if file is referenced via cluster

module.exports = startServer;

}



In this example, we host a basic web server, however, we spin up workers (child processes) using the built-in

cluster module. The number of processes forker depend on the number of CPU cores available. This enables a

Node.js application to take advantage of multi-core CPUs, since a single instance of Node.js runs in a single thread.

The application will now share the port 8000 across all the processes. Loads will automatically be distributed

between workers using the Round-Robin method by default.



Section 8.2: Cluster Example

A single instance of Node.js runs in a single thread. To take advantage of multi-core systems, application can be

launched in a cluster of Node.js processes to handle the load.



GoalKicker.com – Node.js Notes for Professionals



60



The cluster module allows you to easily create child processes that all share server ports.

Following example create the worker child process in main process that handles the load across multiple cores.

Example

const cluster = require('cluster');

const http = require('http');

const numCPUs = require('os').cpus().length; //number of CPUS

if (cluster.isMaster) {

// Fork workers.

for (var i = 0; i < numCPUs; i++) {

cluster.fork();

//creating child process

}

//on exit of cluster

cluster.on('exit', (worker, code, signal) => {

if (signal) {

console.log(`worker was killed by signal: ${signal}`);

} else if (code !== 0) {

console.log(`worker exited with error code: ${code}`);

} else {

console.log('worker success!');

}

});

} else {

// Workers can share any TCP connection

// In this case it is an HTTP server

http.createServer((req, res) => {

res.writeHead(200);

res.end('hello world\n');

}).listen(3000);

}



GoalKicker.com – Node.js Notes for Professionals



61



Chapter 9: Readline

Section 9.1: Line-by-line file reading

const fs = require('fs');

const readline = require('readline');

const rl = readline.createInterface({

input: fs.createReadStream('text.txt')

});

// Each new line emits an event - every time the stream receives \r, \n, or \r\n

rl.on('line', (line) => {

console.log(line);

});

rl.on('close', () => {

console.log('Done reading file');

});



Section 9.2: Prompting user input via CLI

const readline = require('readline');

const rl = readline.createInterface({

input: process.stdin,

output: process.stdout

});

rl.question('What is your name?', (name) => {

console.log(`Hello ${name}!`);

rl.close();

});



GoalKicker.com – Node.js Notes for Professionals



62



Chapter 10: package.json

Section 10.1: Exploring package.json

A package.json file, usually present in the project root, contains metadata about your app or module as well as the

list of dependencies to install from npm when running npm install.

To initialize a package.json type npm init in your command prompt.

To create a package.json with default values use:

npm init --yes

# or

npm init -y



To install a package and save it to package.json use:

npm install {package name} --save



You can also use the shorthand notation:

npm i -S {package name}



NPM aliases -S to --save and -D to --save-dev to save in your production or development dependencies

respectively.

The package will appear in your dependencies; if you use --save-dev instead of --save, the package will appear in

your devDependencies.

Important properties of package.json:

{

"name": "module-name",

"version": "10.3.1",

"description": "An example module to illustrate the usage of a package.json",

"author": "Your Name ",

"contributors": [{

"name": "Foo Bar",

"email": "foo.bar@example.com"

}],

"bin": {

"module-name": "./bin/module-name"

},

"scripts": {

"test": "vows --spec --isolate",

"start": "node index.js",

"predeploy": "echo About to deploy",

"postdeploy": "echo Deployed",

"prepublish": "coffee --bare --compile --output lib/foo src/foo/*.coffee"

},

"main": "lib/foo.js",

"repository": {

"type": "git",

"url": "https://github.com/username/repo"

},

"bugs": {

"url": "https://github.com/username/issues"



GoalKicker.com – Node.js Notes for Professionals



63



Xem Thêm
Tải bản đầy đủ (.pdf) (334 trang)

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×