Nodejs Process
We all know that Node.js runs in a single-threaded mode, but it uses event-driven handling for concurrency, which helps us create multiple child processes on multi-core CPU systems, thereby improving performance.\\n\\nEach child process always has three stream objects: child.stdin, child.stdout, and child.stderr. They may share the parent process's stdio streams, or they can be independent piped stream objects.\\n\\nNode provides the child_process and cluster modules to create child processes.\\n\\n**`child_process` Module**\\n\\n* **exec** - child_process.exec uses a child process to execute a command, buffers the child process's output, and returns the child process's output as a callback function parameter.\\n\\n* **execFile** - Directly executes an executable file, slightly more secure.\\n\\n* **spawn** - child_process.spawn creates a new process using specified command-line arguments.\\n\\n* **fork** - child_process.fork is a special form of spawn(), used for modules running in a child process, such as fork('./son.js') which is equivalent to spawn('node', ['./son.js']). Unlike the spawn method, fork establishes a communication channel between the parent process and the child process for inter-process communication.\\n\\n**`cluster` Module**\\n\\n* **Multiple worker processes** share listening on a single port, implementing a **one process per core** HTTP service.\\n* Suitable for horizontally utilizing multiple cores for Web services.\\n* Note: The official recommendation is for new projects to carefully evaluate (such as using reverse proxy + multiple processes directly, or `worker_threads` for CPU-intensive tasks), but `cluster` remains widely available.\\n\\n* * *\\n\\n## exec() Method\\n\\nchild_process.exec uses a child process to execute a command, buffers the child process's output, and returns the child process's output as a callback function parameter.\\n\\nThe syntax is as follows:\\n\\nchild_process.exec(command[, options], callback)\\n### Parameters\\n\\nParameter descriptions are as follows:\\n\\n**command:** String, the command to be run, with arguments separated by spaces\\n\\n**options:** Object, which can be:\\n\\n* cwd, String, the current working directory of the child process\\n* env, Object, environment variable key-value pairs\\n* encoding, String, character encoding (default: 'utf8')\\n* shell, String, the Shell to execute the command (default: `/bin/sh` in UNIX, `cmd.exe` in Windows. The Shell should be able to recognize the `-c` switch in UNIX, or `/s /c` in Windows. In Windows, command-line parsing should be compatible with `cmd.exe`)\\n* timeout, Number, timeout duration (default: 0)\\n* maxBuffer, Number, the maximum buffer allowed in stdout or stderr (binary), if exceeded, the child process will be killed (default: 200*1024)\\n* killSignal, String, termination signal (default: 'SIGTERM')\\n* uid, Number, sets the user process ID\\n* gid, Number, sets the process group ID\\n\\n**callback:** Callback function, containing three parameters error, stdout, and stderr.\\n\\nThe exec() method returns the maximum buffer and waits for the process to end, returning the buffer's content all at once.\\n\\n### Instance\\n\\nLet's create two js files: support.js and master.js.\\n\\n## support.js file code:\\n\\nconsole.log("Process " + process.argv + " Executing.");\\n\\n## master.js file code:\\n\\nconst fs = require('fs'); const child_process = require('child_process'); for(var i=0; i<3; i++){var workerProcess = child_process.exec('node support.js '+i, function(error, stdout, stderr){if(error){console.log(error.stack); console.log('Error code: '+error.code); console.log('Signal received: '+error.signal); }console.log('stdout: ' + stdout); console.log('stderr: ' + stderr); }); workerProcess.on('exit', function(code){console.log('Child process has exited, exit code '+code); }); }\\n\\nExecute the above code, the output result is:\\n\\n$ node master.js Child process has exited, exit code 0 stdout: Process 1 executing. stderr: Child process has exited, exit code 0 stdout: Process 0 executing. stderr: Child process has exited, exit code 0 stdout: Process 2 executing. stderr: \\n**Explanation:**\\n\\n`exec` will start **3 child processes**, executing respectively:\\n\\n* `node support.js 0`\\n* `node support.js 1`\\n* `node support.js 2`\\n\\nAfter each child process runs, it immediately outputs:\\n\\nProcess 0 executing. Process 1 executing. Process 2 executing.\\nThis part is the **standard output (stdout)** of the child process, which will be buffered and passed back to the `exec` callback together when the child process ends.\\n\\nWhen the child process exits, the `exit` event is triggered first, and then the `exec` callback is executed (Note: Node.js documentation states that the **`exit` event occurs when the process ends**, while the `exec` callback is triggered after the `stdio` streams are closed; usually, exit prints before the callback).\\n\\n**The output order is uncertain**, because the 3 child processes execute in parallel, and who finishes first depends on the operating system's scheduling.\\n\\n* * *\\n\\n## spawn() Method\\n\\nchild_process.spawn creates a new process using specified command-line arguments, the syntax format is as follows:\\n\\nchild_process.spawn(command[, args][, options])\\n### Parameters\\n\\nParameter descriptions are as follows:\\n\\n**command:** The command to be run\\n\\n**args:** Array of string arguments\\n\\n**options Object**\\n\\n* cwd String The current working directory of the child process\\n* env Object Environment variable key-value pairs\\n* stdio Array|String The child process's stdio configuration\\n* detached Boolean This child process will become the leader of the process group\\n* uid Number Sets the user process ID\\n* gid Number Sets the process group ID\\n\\nThe spawn() method returns streams (stdout & stderr) and is used when the process returns a large amount of data. spawn() starts receiving responses as soon as the process begins executing.\\n\\n### Instance\\n\\nLet's create two js files: support.js and master.js.\\n\\n## support.js file code:\\n\\nconsole.log("Process " + process.argv + " Executing.");\\n\\n## master.js file code:\\n\\nconst fs = require('fs'); const child_process = require('child_process'); for(var i=0; i<3; i++){var workerProcess = child_process.spawn('node', ['support.js', i]); workerProcess.stdout.on('data', function(data){console.log('stdout: ' + data); }); workerProcess.stderr.on('data', function(data){console.log('stderr: ' + data); }); workerProcess.on('close', function(code){console.log('Child process has exited, exit code '+code); }); }\\n\\nExecute the above code, the output result is:\\n\\n$ node master.js stdout: Process 0 executed. Child process has exited, exit code 0 stdout: Process 1 executed. Child process has exited, exit code 0 stdout: Process 2 executed. Child process has exited, exit code 0\\n\\n* * *\\n\\n## fork Method\\n\\nchild_process.fork is a special form of the spawn() method, used to create processes, the syntax format is as follows:\\n\\nchild_process.fork(modulePath[, args][, options])\\n### Parameters\\n\\nParameter descriptions are as follows:\\n\\n**modulePath**: String, the module to be run in the child process\\n\\n**args**: Array of string arguments\\n\\n**options**: Object\\n\\n* cwd String The current working directory of the child process\\n* env Object Environment variable key-value pairs\\n* execPath String The executable file to create the child process\\n* execArgv Array Array of string arguments for the child process's executable file (default: process.execArgv)\\n* silent Boolean If `true`, the child process's `stdin`, `stdout`, and `stderr` will be associated with the parent process, otherwise, they will be inherited from the parent process. (Default: `false`)\\n* uid Number Sets the user process ID\\n* gid Number Sets the process group ID\\n\\nThe returned object has all the methods of a ChildProcess instance, plus a built-in communication channel.\\n\\n### Instance\\n\\nLet's create two js files: support.js and master.js.\\n\\n## support.js file code:\\n\\nconsole.log("Process " + process.argv + " Executing.");\\n\\n## master.js file code:\\n\\nconst fs = require('fs'); const child_process = require('child_process'); for(var i=0; i<3; i++){var worker_process = child_process.fork("support.js", ); worker_process.on('close', function(code){console.log('Child process has exited, exit code ' + code); }); }\\n\\nExecute the above code, the output result is:\\n\\n$ node master.js Process 0 executed. Child process has exited, exit code 0Process 1 executed. Child process has exited, exit code 0Process 2 executed. Child process has exited, exit code 0\\n\\n* * *\\n\\n## cluster: Multi-process HTTP Service on a Single Port\\n\\n### Minimal viable multi-core HTTP service\\n\\n## Instance\\n\\n// server-cluster.js\\n\\nimport cluster from 'node:cluster';\\n\\nimport os from 'node:os';\\n\\nimport http from 'node:http';\\n\\nimport{ pbkdf2Sync } from 'node:crypto';\\n\\nif(cluster.isPrimary){\\n\\nconst cpuCount =Math.max(1, os.cpus().length);\\n\\n console.log(`Main process ${process.pid}οΌStart ${cpuCount} Worker process`);\\n\\nfor(let i =0; i < cpuCount; i++) cluster.fork();\\n\\ncluster.on('exit',(worker, code)=>{\\n\\n console.warn
YouTip