Hướng dẫn process nodejs - xử lý nodejs

Tiến trình là một đối tượng toàn cục, một thể hiện của EventEmitter, có thể được truy cập từ bất cứ đâu.

Các bài viết liên quan:

  • Thuộc tính Process Node.js
  • Ví dụ về thuộc tính quy trình Node.js
  • Các chức năng của quy trình Node.js
  • Ví dụ về hàm xử lý Node.js

Thuộc tính Process Node.js

Ví dụ về thuộc tính quy trình Node.js

Các chức năng của quy trình Node.js Ví dụ về hàm xử lý Node.js
Dưới đây là danh sách các thuộc tính quy trình Node.js thường được sử dụng.Property
Descriptionarch
trả về kiến ​​trúc quy trình: ‘arm’, ‘ia32’ hoặc ‘x64’ args
trả về các đối số dòng lệnh dưới dạng một mảng env
trả về môi trường người dùng pid
trả về id quy trình của quy trình platform
trả về nền tảng của quy trình: ‘darwin’, ‘freebsd’, ‘linux’, ‘sunos’ hoặc ‘win32’ release
trả về siêu dữ liệu cho bản phát hành nút hiện tại version

Ví dụ về thuộc tính quy trình Node.js

Các chức năng của quy trình Node.jsđể in kiến ​​trúc, pid, nền tảng và phiên bản của quy trình.

Ví dụ về hàm xử lý Node.js

console.log(`Process Architecture: ${process.arch}`);  
	console.log(`Process PID: ${process.pid}`);  
 	console.log(`Process Platform: ${process.platform}`);  
 	console.log(`Process Version: ${process.version}`);  

Dưới đây là danh sách các thuộc tính quy trình Node.js thường được sử dụng.

Propertyví dụ quy trình khác để in các đối số dòng lệnh . Ở đây nút được coi là đối số đầu tiên, tên tệp được coi là đối số thứ hai và các đối số dòng lệnh thực tế được coi là đối số thứ ba, thứ tư, thứ năm, v.v.

Description

 	process.argv.forEach((value, index, array) => {  
  	  console.log(`${index}: ${value}`);  
 	});  

Dưới đây là danh sách các thuộc tính quy trình Node.js thường được sử dụng.

Các chức năng của quy trình Node.js

Ví dụ về hàm xử lý Node.js

Dưới đây là danh sách các thuộc tính quy trình Node.js thường được sử dụng. Ví dụ về hàm xử lý Node.js
Dưới đây là danh sách các thuộc tính quy trình Node.js thường được sử dụng.Property
Descriptionarch
trả về kiến ​​trúc quy trình: ‘arm’, ‘ia32’ hoặc ‘x64’ args
trả về các đối số dòng lệnh dưới dạng một mảng env
trả về môi trường người dùng pid

Ví dụ về hàm xử lý Node.js

Dưới đây là danh sách các thuộc tính quy trình Node.js thường được sử dụng.ví dụ quy trình để in thư mục làm việc hiện tại và thời gian hoạt động của quy trình.

Property

console.log(`Current directory: ${process.cwd()}`);  
console.log(`Uptime: ${process.uptime()}`);  

Dưới đây là danh sách các thuộc tính quy trình Node.js thường được sử dụng.

Trong bài viết này, chúng ta sẽ cùng tìm hiểu về việc quản lý tiến trình vận hành phần mềm - hay còn được gọi là

 	process.argv.forEach((value, index, array) => {  
  	  console.log(`${index}: ${value}`);  
 	});  
1 - và một vài công cụ do NodeJS cung cấp để hỗ trợ việc tạo ra và quản lý các tiến trình vận hành code. Tuy nhiên trước khi bắt đầu thảo luận về các công cụ do NodeJS cung cấp, chúng ta cần xem một
 	process.argv.forEach((value, index, array) => {  
  	  console.log(`${index}: ${value}`);  
 	});  
1 được biểu thị như thế nào trong môi trường hệ điều hành mà chúng ta đang sử dụng.

Nếu như bạn đang sử dụng Windows thì có thể tìm và mở phần mềm

 	process.argv.forEach((value, index, array) => {  
  	  console.log(`${index}: ${value}`);  
 	});  
3 hoặc
 	process.argv.forEach((value, index, array) => {  
  	  console.log(`${index}: ${value}`);  
 	});  
4 để xem danh sách tất cả các tiến trình vận hành phần mềm đang được quản lý bởi hệ thống. Ví dụ trong ảnh chụp màn hình minh họa dưới đây thì mỗi một
 	process.argv.forEach((value, index, array) => {  
  	  console.log(`${index}: ${value}`);  
 	});  
1 được
 	process.argv.forEach((value, index, array) => {  
  	  console.log(`${index}: ${value}`);  
 	});  
4 biểu thị bằng một hàng trong bảng
 	process.argv.forEach((value, index, array) => {  
  	  console.log(`${index}: ${value}`);  
 	});  
7; Và được gắn với một mã
 	process.argv.forEach((value, index, array) => {  
  	  console.log(`${index}: ${value}`);  
 	});  
8 ở cột thứ hai để phân biệt với các tiến trình khác.

Hướng dẫn process nodejs - xử lý nodejs

Ồ... mình đang sử dụng duy nhất một cửa sổ Firefox với 1 tab đang soạn thảo bài viết tại đây, nhưng lại có tới 10 tiến trình

 	process.argv.forEach((value, index, array) => {  
  	  console.log(`${index}: ${value}`);  
 	});  
9 khác nhau đang hoạt động song song. Để mình thử mở một phần mềm đơn giản hơn xem kết quả thế nào, Notepad chắc là đơn giản nhất rồi.

Hướng dẫn process nodejs - xử lý nodejs

Hm... Một cửa sổ Notepad chỉ sử dụng duy nhất một tiến trình. Như vậy là một phần mềm, như chúng ta đã thấy, có thể sử dụng nhiều tiến trình để thực hiện các công việc ở phía sau giao diện người dùng. Và ở trong bảng

 	process.argv.forEach((value, index, array) => {  
  	  console.log(`${index}: ${value}`);  
 	});  
4 vừa nãy thì cũng có rất nhiều những phần mềm khác không thể hiện trên giao diện người dùng, giống như phần mềm
console.log(`Current directory: ${process.cwd()}`);  
console.log(`Uptime: ${process.uptime()}`);  
1 của trang blog đơn giản mà chúng ta đã viết, cũng sử dụng nhiều tiến trình vận hành song song.

Các module quản lý tiến trình

Cũng như các ứng dụng khác trong cùng thiết bị, mỗi ứng dụng NodeJS mà chúng ta lập trình cũng sẽ được vận hành trên một hoặc nhiều tiến trình.

Cụ thể là chúng ta sẽ luôn có một tiến trình chính

console.log(`Current directory: ${process.cwd()}`);  
console.log(`Uptime: ${process.uptime()}`);  
2, gắn liền với tệp mà chúng ta khởi chạy với lệnh
console.log(`Current directory: ${process.cwd()}`);  
console.log(`Uptime: ${process.uptime()}`);  
3. Vì vậy nên trong nhiều ngôn ngữ lập trình, hàm khởi đầu chương trình có tên mặc định là
console.log(`Current directory: ${process.cwd()}`);  
console.log(`Uptime: ${process.uptime()}`);  
4 - có nghĩa là bắt đầu tiến trình chính.

Các tiến trình phụ (nếu có) sẽ được đặt tên theo

console.log(`Current directory: ${process.cwd()}`);  
console.log(`Uptime: ${process.uptime()}`);  
5 riêng tùy vào
console.log(`Current directory: ${process.cwd()}`);  
console.log(`Uptime: ${process.uptime()}`);  
6 và người viết code. Tuy nhiên ở lớp cơ sở thì NodeJS gọi là các tiến trình con
console.log(`Current directory: ${process.cwd()}`);  
console.log(`Uptime: ${process.uptime()}`);  
7.

Và tương ứng với hai loại tiến trình này, NodeJS có cung cấp 2 module khởi điểm cung cấp giao diện lập trình cho chúng ta có thể chủ động tạo ra và quản lý các tiến trình là:

  • Module
     	process.argv.forEach((value, index, array) => {  
      	  console.log(`${index}: ${value}`);  
     	});  
    
    1 - cung cấp object
     	process.argv.forEach((value, index, array) => {  
      	  console.log(`${index}: ${value}`);  
     	});  
    
    1 mô tả tiến trình chính
    console.log(`Current directory: ${process.cwd()}`);  
    console.log(`Uptime: ${process.uptime()}`);  
    2.
  • Module
    const process = require(`process`);
    const http = require(`http`);
    
       /* --- Create a server */
    
    const handleRequest = function(request, response) {
       var html = `
          

    Process

    Title: ${process.title}

    ID: ${process.pid}

    OS: ${process.platform}

    `
    ; // html response.setHeader(`content-type`, `text/html`); response.statusCode = 200; response.end(html); }; const server = http.createServer(handleRequest); /* --- Start server */ const port = 3000; const hostname = `127.0.0.1`; const callback = function() { console.log(`Server is running at...`); console.log(`http://${hostname}:${port}/`); }; server.listen(port, hostname, callback);
    1 - cung cấp
    const process = require(`process`);
    const http = require(`http`);
    
       /* --- Create a server */
    
    const handleRequest = function(request, response) {
       var html = `
          

    Process

    Title: ${process.title}

    ID: ${process.pid}

    OS: ${process.platform}

    `
    ; // html response.setHeader(`content-type`, `text/html`); response.statusCode = 200; response.end(html); }; const server = http.createServer(handleRequest); /* --- Start server */ const port = 3000; const hostname = `127.0.0.1`; const callback = function() { console.log(`Server is running at...`); console.log(`http://${hostname}:${port}/`); }; server.listen(port, hostname, callback);
    2 và các phương thức khởi tạo các tiến trình con sử dụng class này.

Main process

Mặc dù object

 	process.argv.forEach((value, index, array) => {  
  	  console.log(`${index}: ${value}`);  
 	});  
1 được gắn với object môi trường toàn cục
const process = require(`process`);
const http = require(`http`);

   /* --- Create a server */

const handleRequest = function(request, response) {
   var html = `
      

Process

Title: ${process.title}

ID: ${process.pid}

OS: ${process.platform}

`
; // html response.setHeader(`content-type`, `text/html`); response.statusCode = 200; response.end(html); }; const server = http.createServer(handleRequest); /* --- Start server */ const port = 3000; const hostname = `127.0.0.1`; const callback = function() { console.log(`Server is running at...`); console.log(`http://${hostname}:${port}/`); }; server.listen(port, hostname, callback);
4 và có thể được truy xuất ở bất kỳ đâu trong
console.log(`Current directory: ${process.cwd()}`);  
console.log(`Uptime: ${process.uptime()}`);  
6. Tuy nhiên tài liệu của NodeJS khuyến khích thực hiện thêm thao tác
const process = require(`process`);
const http = require(`http`);

   /* --- Create a server */

const handleRequest = function(request, response) {
   var html = `
      

Process

Title: ${process.title}

ID: ${process.pid}

OS: ${process.platform}

`
; // html response.setHeader(`content-type`, `text/html`); response.statusCode = 200; response.end(html); }; const server = http.createServer(handleRequest); /* --- Start server */ const port = 3000; const hostname = `127.0.0.1`; const callback = function() { console.log(`Server is running at...`); console.log(`http://${hostname}:${port}/`); }; server.listen(port, hostname, callback);
6 trong tệp cần sử dụng. Ở đây chúng ta sẽ sử dụng lại code server "Hello World" từ những bài viết đầu tiên của Sub-Series này để hiển thị một số thông tin về
console.log(`Current directory: ${process.cwd()}`);  
console.log(`Uptime: ${process.uptime()}`);  
2.

const process = require(`process`);
const http = require(`http`);

   /* --- Create a server */

const handleRequest = function(request, response) {
   var html = `
      

Process

Title: ${process.title}

ID: ${process.pid}

OS: ${process.platform}

`
; // html response.setHeader(`content-type`, `text/html`); response.statusCode = 200; response.end(html); }; const server = http.createServer(handleRequest); /* --- Start server */ const port = 3000; const hostname = `127.0.0.1`; const callback = function() { console.log(`Server is running at...`); console.log(`http://${hostname}:${port}/`); }; server.listen(port, hostname, callback);
cd Desktop
node main.js

http://127.0.0.1:3000/

Hướng dẫn process nodejs - xử lý nodejs

Child process

Các tiến trình con có thể được tạo ra bởi nhiều phương thức khác nhau và NodeJS có cung cấp một vài module khác nữa để thực hiện việc này. Tuy nhiên tất cả đều được xây dựng dựa trên giao diện lập trình do module

const process = require(`process`);
const http = require(`http`);

   /* --- Create a server */

const handleRequest = function(request, response) {
   var html = `
      

Process

Title: ${process.title}

ID: ${process.pid}

OS: ${process.platform}

`
; // html response.setHeader(`content-type`, `text/html`); response.statusCode = 200; response.end(html); }; const server = http.createServer(handleRequest); /* --- Start server */ const port = 3000; const hostname = `127.0.0.1`; const callback = function() { console.log(`Server is running at...`); console.log(`http://${hostname}:${port}/`); }; server.listen(port, hostname, callback);
1 cung cấp. Và phương thức cơ bản nhất có tên là
const process = require(`process`);
const http = require(`http`);

   /* --- Create a server */

const handleRequest = function(request, response) {
   var html = `
      

Process

Title: ${process.title}

ID: ${process.pid}

OS: ${process.platform}

`
; // html response.setHeader(`content-type`, `text/html`); response.statusCode = 200; response.end(html); }; const server = http.createServer(handleRequest); /* --- Start server */ const port = 3000; const hostname = `127.0.0.1`; const callback = function() { console.log(`Server is running at...`); console.log(`http://${hostname}:${port}/`); }; server.listen(port, hostname, callback);
9 - được sử dụng để chạy một câu lệnh trong cửa sổ dòng lệnh như chúng ta thường thao tác trên giao diện đồ họa.

child_process.spawn(command[, args][, options]);

Trong cú pháp của

const process = require(`process`);
const http = require(`http`);

   /* --- Create a server */

const handleRequest = function(request, response) {
   var html = `
      

Process

Title: ${process.title}

ID: ${process.pid}

OS: ${process.platform}

`
; // html response.setHeader(`content-type`, `text/html`); response.statusCode = 200; response.end(html); }; const server = http.createServer(handleRequest); /* --- Start server */ const port = 3000; const hostname = `127.0.0.1`; const callback = function() { console.log(`Server is running at...`); console.log(`http://${hostname}:${port}/`); }; server.listen(port, hostname, callback);
9 được cung cấp bởi tài liệu của NodeJS thì tạm thời chúng ta sẽ chỉ quan tâm tới
cd Desktop
node main.js
1 và
cd Desktop
node main.js
2. Ví dụ khi chúng ta chạy một câu lệnh nào đó trong cửa sổ dòng lệnh ví dụ như
cd Desktop
node main.js
3; thì
cd Desktop
node main.js
4 là lệnh cần thực thi
cd Desktop
node main.js
1, và phần còn lại đều là các tham số
cd Desktop
node main.js
6.

var command = 'npm';
var args = ['install', '--save', 'something'];
var subprocess = child_process.spawn(command, args);

Phương thức này mở ra một tiềm năng mới giúp chúng ta có thể chạy một phần mềm khác trong cùng thiết bị từ code viết trên nền NodeJS. Ví dụ như mở một trình duyệt web và trỏ tới một địa chỉ web nào đó, hoặc chạy một

cd Desktop
node main.js
7 được viết trên một ngôn ngữ khác, v.v...

Nói riêng về việc chạy một

cd Desktop
node main.js
7 khác để ủy thác một tác vụ cần xử lý song song, nếu như chúng ta muốn sử dụng một
cd Desktop
node main.js
7 được viết bằng JavaScript thì NodeJS có cung cấp một phương thức khác tên là
child_process.spawn(command[, args][, options]);
0. Phương thức này được xây dựng dựa trên
const process = require(`process`);
const http = require(`http`);

   /* --- Create a server */

const handleRequest = function(request, response) {
   var html = `
      

Process

Title: ${process.title}

ID: ${process.pid}

OS: ${process.platform}

`
; // html response.setHeader(`content-type`, `text/html`); response.statusCode = 200; response.end(html); }; const server = http.createServer(handleRequest); /* --- Start server */ const port = 3000; const hostname = `127.0.0.1`; const callback = function() { console.log(`Server is running at...`); console.log(`http://${hostname}:${port}/`); }; server.listen(port, hostname, callback);
9 nhưng được bổ sung thêm nhiều tiện ích hỗ trợ viết code giao tiếp giữa
console.log(`Current directory: ${process.cwd()}`);  
console.log(`Uptime: ${process.uptime()}`);  
2 và
console.log(`Current directory: ${process.cwd()}`);  
console.log(`Uptime: ${process.uptime()}`);  
7 đơn giản hơn.

var subprocess = child_process.fork("đường-dẫn-tới-module");

Giao tiếp giữa các process

Hãy tạm lấy ví dụ một trường hợp sử dụng

const process = require(`process`);
const http = require(`http`);

   /* --- Create a server */

const handleRequest = function(request, response) {
   var html = `
      

Process

Title: ${process.title}

ID: ${process.pid}

OS: ${process.platform}

`
; // html response.setHeader(`content-type`, `text/html`); response.statusCode = 200; response.end(html); }; const server = http.createServer(handleRequest); /* --- Start server */ const port = 3000; const hostname = `127.0.0.1`; const callback = function() { console.log(`Server is running at...`); console.log(`http://${hostname}:${port}/`); }; server.listen(port, hostname, callback);
1 đơn giản nhất, đó là khi chúng ta muốn tách rời một tác vụ tính toán phức tạp để thực hiện song song với
console.log(`Current directory: ${process.cwd()}`);  
console.log(`Uptime: ${process.uptime()}`);  
2. Như vậy chương trình của chúng ta sẽ có thể thực hiện những công việc khác nữa, trong thời gian chờ kết quả tính toán được trả về.

Đây là trường hợp cơ bản và phổ biến tới mức các ngôn ngữ lập trình đều cung cấp một giao diện dựng sẵn như một cú pháp hoặc một phương thức cho phép phát động một lời gọi hàm trên tiến trình song song. Trong JavaScript thì chúng ta đã biết tới các hàm

child_process.spawn(command[, args][, options]);
6; và ở đây thì chúng ta sẽ làm một ví dụ đơn giản với
child_process.spawn(command[, args][, options]);
0 để mô phỏng lại một thao tác được thực thi bất đồng bộ.

const child_process = require(`child_process`);

console.log(`Ủy thác tác vụ tính toán phức tạp cho module async...`);

var subprocess = child_process.fork(`./async`);

subprocess.on(`message`, (message) => {
   console.log(`Kết quả từ module async: ${message.result}`);
   subprocess.kill();   // kết thúc subprocess
});

subprocess.send({ parameter: 1001 });

console.log(`Đây là một tác vụ khác trên main process...`);

Trong code ví dụ

child_process.spawn(command[, args][, options]);
8 ở trên, chúng ta đã tạo ra một
child_process.spawn(command[, args][, options]);
9 từ module
var command = 'npm';
var args = ['install', '--save', 'something'];
var subprocess = child_process.spawn(command, args);
0 trong cùng thư mục. Sau đó gắn một
var command = 'npm';
var args = ['install', '--save', 'something'];
var subprocess = child_process.spawn(command, args);
1 vào
child_process.spawn(command[, args][, options]);
9 để chờ thông báo kết quả tính toán được ủy thác từ
var command = 'npm';
var args = ['install', '--save', 'something'];
var subprocess = child_process.spawn(command, args);
3.

Phương thức

var command = 'npm';
var args = ['install', '--save', 'something'];
var subprocess = child_process.spawn(command, args);
4 sẽ phát động một sự kiện bằng
var command = 'npm';
var args = ['install', '--save', 'something'];
var subprocess = child_process.spawn(command, args);
5 kèm theo một kênh truyền dữ liệu trừu tượng được lập trình sẵn mà chúng ta không cần biết chi tiết. Lúc này code ở
var command = 'npm';
var args = ['install', '--save', 'something'];
var subprocess = child_process.spawn(command, args);
0 cũng có thể gắn
var command = 'npm';
var args = ['install', '--save', 'something'];
var subprocess = child_process.spawn(command, args);
1 vào
console.log(`Current directory: ${process.cwd()}`);  
console.log(`Uptime: ${process.uptime()}`);  
2 để chờ thông báo tham số được truyền tới. Ngay khi nhận được tham số thì
child_process.spawn(command[, args][, options]);
6 sẽ thực hiện tính toán và thông báo lại sớm nhất có thể.

var process = require(`process`);

process.on(`message`, (message) => {
   // --- giả lập một tác vụ tính toán sau khi nhận được tham số
   // --- thời gian thực hiện khoảng 10 giây sau đó trả về kết quả
   var delay = 10 * 1000;
   setTimeout((_) => {
      process.send({ result: message.parameter - 900 });
   }, delay);
});
 	process.argv.forEach((value, index, array) => {  
  	  console.log(`${index}: ${value}`);  
 	});  
0

Kết thúc bài viết

Như vậy là chúng ta đã thực hiện xong phần giới thiệu sơ lược về các công cụ cơ bản hỗ trợ tạo ra và quản lý các tiến trình vận hành phần mềm trong NodeJS. Nói riêng về nhu cầu cần sử dụng các

cd Desktop
node main.js
7 viết trên các ngôn ngữ khác, phương thức giao tiếp giữa các
 	process.argv.forEach((value, index, array) => {  
  	  console.log(`${index}: ${value}`);  
 	});  
1 sẽ có phần phức tạp hơn một chút. Lý do là vì
const process = require(`process`);
const http = require(`http`);

   /* --- Create a server */

const handleRequest = function(request, response) {
   var html = `
      

Process

Title: ${process.title}

ID: ${process.pid}

OS: ${process.platform}

`
; // html response.setHeader(`content-type`, `text/html`); response.statusCode = 200; response.end(html); }; const server = http.createServer(handleRequest); /* --- Start server */ const port = 3000; const hostname = `127.0.0.1`; const callback = function() { console.log(`Server is running at...`); console.log(`http://${hostname}:${port}/`); }; server.listen(port, hostname, callback);
9 là phương thức cơ sở và không được tích hợp tính năng giao tiếp qua
var subprocess = child_process.fork("đường-dẫn-tới-module");
3 như
child_process.spawn(command[, args][, options]);
0.

Để có thể sử dụng được

const process = require(`process`);
const http = require(`http`);

   /* --- Create a server */

const handleRequest = function(request, response) {
   var html = `
      

Process

Title: ${process.title}

ID: ${process.pid}

OS: ${process.platform}

`
; // html response.setHeader(`content-type`, `text/html`); response.statusCode = 200; response.end(html); }; const server = http.createServer(handleRequest); /* --- Start server */ const port = 3000; const hostname = `127.0.0.1`; const callback = function() { console.log(`Server is running at...`); console.log(`http://${hostname}:${port}/`); }; server.listen(port, hostname, callback);
9 và ủy thác tác vụ tính toán cho một
cd Desktop
node main.js
7 viết bởi ngôn ngữ khác hoặc một
var subprocess = child_process.fork("đường-dẫn-tới-module");
7 bất kỳ có giao diện sử dụng dòng lệnh, chúng ta sẽ cần chuẩn bị thêm một chút kiến thức về
var subprocess = child_process.fork("đường-dẫn-tới-module");
8. Đây cũng sẽ là chủ đề của bài viết tiếp theo.
Hướng dẫn process nodejs - xử lý nodejs

[NodeJS] Bài 10 - Standard I/O & Stream