Node.js gyermekfolyamatok: Minden, amit tudnia kell

A spawn (), az exec (), az execFile () és a fork () használata

Frissítés: Ez a cikk most a „Node.js Beyond The Basics” című könyvem része.

Olvassa el ennek a tartalomnak a frissített verzióját és többet a Node-ról a jscomplete.com/node-beyond-basics címen .

A Node.js egyszálú, nem blokkoló teljesítménye egyetlen folyamathoz kiválóan működik. De végül egy processzor egyetlen folyamata nem lesz elegendő az alkalmazás növekvő terhelésének kezeléséhez.

Nem számít, milyen erős a kiszolgáló, egyetlen szál csak korlátozott terhelést támogat.

Az a tény, hogy a Node.js egyetlen szálon fut, nem jelenti azt, hogy nem használhatjuk ki a több folyamat, és természetesen a több gép előnyeit sem.

A Node alkalmazás méretezésének legjobb módja a több folyamat használata. A Node.js sok csomópontot tartalmazó elosztott alkalmazások kiépítésére készült. Ezért nevezik Node-nak . A skálázhatóság belemerül a platformba, és nem ez az, amire később egy alkalmazás élettartama során gondolni kezd.

Ez a cikk a Node.js-ről szóló Pluralsight tanfolyamom egy része. Én hasonló tartalmat fedek le videó formátumban ott.

Felhívjuk figyelmét, hogy a cikk elolvasása előtt jól meg kell ismernie a Node.js eseményeit és folyamait . Ha még nem tette meg, javasoljuk, hogy olvassa el ezt a két másik cikket, mielőtt elolvassa ezt:

A Node.js eseményvezérelt architektúrájának megértése

A Node legtöbb objektuma - például a HTTP kérések, válaszok és adatfolyamok - az EventEmitter modult valósítja meg, így képesek…

Patakok: Minden, amit tudnod kell

A Node.js adatfolyamok arról híresek, hogy nehéz vele dolgozni, és még nehezebb megérteni őket. Nos, van egy jó hírem ...

A Gyermek folyamatok modul

A Node child_processmodul segítségével könnyen megpörgethetjük a gyermekfolyamatokat, és ezek a gyermekfolyamatok könnyen kommunikálhatnak egymással egy üzenetkezelő rendszerrel.

A child_processmodul lehetővé teszi számunkra, hogy hozzáférjünk az operációs rendszer funkcióihoz, futtatva bármilyen rendszerparancsot egy, jól, gyermek folyamatban.

Irányíthatjuk a gyermek folyamat bemeneti adatfolyamát, és meghallgathatjuk a kimeneti adatfolyamát. Vezérelhetjük az alapul szolgáló operációsrendszer-parancsnak továbbítandó argumentumokat is, és bármit megtehetünk a parancs kimenetével. Például csempézhetjük az egyik parancs kimenetét bemenetként a másikba (csakúgy, mint a Linuxban), mivel a parancsok összes be- és kimenete bemutatható nekünk a Node.js adatfolyamok segítségével.

Vegye figyelembe, hogy a cikkben használt példák mind Linux alapúak. Windows rendszeren át kell váltania az általam használt parancsokat a Windows alternatíváival.

Négy különböző módon lehet létrehozni egy gyermek folyamatot Csomópont: spawn(), fork(), exec()és execFile().

Meglátjuk a különbségeket e négy funkció és az egyes funkciók között.

Született gyermeki folyamatok

A spawnfüggvény elindít egy parancsot egy új folyamatban, és használhatjuk a parancs bármely argumentumának átadására. Például itt van egy kód egy új folyamat létrehozásához, amely végrehajtja a pwdparancsot.

const { spawn } = require('child_process'); const child = spawn('pwd');

Egyszerűen lebontjuk a spawnfüggvényt a child_processmodulból, és az OS paranccsal hajtjuk végre első argumentumként.

A spawnfüggvény (a childfenti objektum) végrehajtásának eredménye egy olyan ChildProcesspélda, amely megvalósítja az EventEmitter API-t. Ez azt jelenti, hogy közvetlenül regisztrálhatunk kezelőket az eseményekre ezen a gyermekobjektumon. Például tehetünk valamit, amikor a gyermek folyamat kilép, regisztrálva egy kezelőt az exiteseményre:

child.on('exit', function (code, signal) { console.log('child process exited with ' + `code ${code} and signal ${signal}`); });

A fenti kezelő megadja nekünk a kimenetet codea gyermek folyamathoz, és signalha van ilyen, akkor a gyermek folyamatának leállításához használtuk. Ez a signalváltozó null, amikor a gyermekfolyamat normálisan kilép.

A másik esemény, hogy mi lehet regisztrálni rakodók a ChildProcesspéldányok disconnect, error, closeés message.

  • Az disconnectesemény akkor jelenik meg, amikor a szülő folyamat manuálisan meghívja a child.disconnectfüggvényt.
  • Az erroresemény akkor jelenik meg, ha a folyamatot nem sikerült előidézni vagy megölni.
  • Az closeesemény akkor jelenik meg, amikor a stdiogyermekfolyamatok bezáródnak.
  • Az messageesemény a legfontosabb. Akkor bocsát ki, amikor a gyermek folyamat a process.send()funkciót használja üzenetek küldésére. A szülő / gyermek folyamatok így tudnak kommunikálni egymással. Az alábbiakban látunk erre egy példát.

Minden gyermek folyamatot is megkapja a három szabványos stdiopatakok, amit használatával hozzáférhet child.stdin, child.stdoutés child.stderr.

Amikor ezek a folyamok bezáródnak, az őket használó gyermekfolyamat fogja kibocsátani az closeeseményt. Ez az closeesemény különbözik az exiteseménytől, mert több gyermekfolyamat is megoszthatja ugyanazokat a stdiofolyamokat, ezért egy gyermekfolyamat kilépése nem jelenti azt, hogy a folyamok bezárultak.

Mivel az összes adatfolyam eseménykibocsátó, különböző eseményeket hallgathatunk azokon az stdioadatfolyamokon, amelyek minden gyermekfolyamathoz kapcsolódnak. A normál folyamattól eltérően a gyermekfolyamatban a stdout/ stderrfolyamok olvasható folyamok, míg a stdinfolyamok írhatóak. Ez alapvetően azoknak a típusoknak a fordítottja, amint az egy fő folyamatban megtalálható. Azok az események, amelyeket ezekhez az adatfolyamokhoz felhasználhatunk, a szokásos események. Ami a legfontosabb, hogy az olvasható adatfolyamokon meghallgathatjuk az dataeseményt, amely a parancs kimenetét vagy bármilyen hibát észlel a parancs végrehajtása során:

child.stdout.on('data', (data) => { console.log(`child stdout:\n${data}`); }); child.stderr.on('data', (data) => { console.error(`child stderr:\n${data}`); });

A fenti két kezelő mindkét esetet naplózza a fő folyamatba stdoutés stderr. Amikor végrehajtjuk a spawnfenti függvényt, a pwdparancs kimenete kinyomtatásra kerül, és a gyermek folyamat kilép kóddal 0, ami azt jelenti, hogy nem történt hiba.

Argumentumokat adhatunk át a spawnfüggvény által végrehajtott parancsnak a függvény második argumentumának felhasználásával spawn, amely a parancsnak továbbítandó összes argumentum tömbje. Például findaz aktuális könyvtár parancsának -type fargumentummal történő végrehajtásához (csak fájlok felsorolásához) a következőket tehetjük:

const child = spawn('find', ['.', '-type', 'f']);

Ha a parancs végrehajtása során hiba lép fel, például ha egy érvénytelen rendeltetési helyet találunk fent, akkor az child.stderrdataeseménykezelő elindul, és az exiteseménykezelő egy kilépési kódot jelent 1, amely azt jelzi, hogy hiba történt. A hibaértékek valójában a gazdagép operációs rendszerétől és a hiba típusától függenek.

A gyermekfolyamat stdinírható adatfolyam. Használhatjuk arra, hogy egy parancsnak valamilyen bemenetet küldjön. Csakúgy, mint bármelyik írható adatfolyam, a legegyszerűbb módja a pipefüggvény használata. Egyszerűen olvasható adatfolyamot vezetünk írható folyamba. Mivel a fő folyamat stdinegy olvasható adatfolyam, ezt egy gyermek folyamatfolyamba vezethetjük be stdin. Például:

const { spawn } = require('child_process'); const child = spawn('wc'); process.stdin.pipe(child.stdin) child.stdout.on('data', (data) => { console.log(`child stdout:\n${data}`); });

In the example above, the child process invokes the wc command, which counts lines, words, and characters in Linux. We then pipe the main process stdin (which is a readable stream) into the child process stdin (which is a writable stream). The result of this combination is that we get a standard input mode where we can type something and when we hit Ctrl+D, what we typed will be used as the input of the wc command.

We can also pipe the standard input/output of multiple processes on each other, just like we can do with Linux commands. For example, we can pipe the stdout of the find command to the stdin of the wc command to count all the files in the current directory:

const { spawn } = require('child_process'); const find = spawn('find', ['.', '-type', 'f']); const wc = spawn('wc', ['-l']); find.stdout.pipe(wc.stdin); wc.stdout.on('data', (data) => { console.log(`Number of files ${data}`); });

I added the -l argument to the wc command to make it count only the lines. When executed, the code above will output a count of all files in all directories under the current one.

Shell Syntax and the exec function

By default, the spawn function does not create a shell to execute the command we pass into it. This makes it slightly more efficient than the exec function, which does create a shell. The exec function has one other major difference. It buffers the command’s generated output and passes the whole output value to a callback function (instead of using streams, which is what spawn does).

Here’s the previous find | wc example implemented with an exec function.

const { exec } = require('child_process'); exec('find . -type f | wc -l', (err, stdout, stderr) => { if (err) { console.error(`exec error: ${err}`); return; } console.log(`Number of files ${stdout}`); });

Since the exec function uses a shell to execute the command, we can use the shell syntax directly here making use of the shell pipe feature.

Note that using the shell syntax comes at a security risk if you’re executing any kind of dynamic input provided externally. A user can simply do a command injection attack using shell syntax characters like ; and $ (for example, command + ’; rm -rf ~’ )

The exec function buffers the output and passes it to the callback function (the second argument to exec) as the stdout argument there. This stdout argument is the command’s output that we want to print out.

The exec function is a good choice if you need to use the shell syntax and if the size of the data expected from the command is small. (Remember, exec will buffer the whole data in memory before returning it.)

The spawn function is a much better choice when the size of the data expected from the command is large, because that data will be streamed with the standard IO objects.

We can make the spawned child process inherit the standard IO objects of its parents if we want to, but also, more importantly, we can make the spawn function use the shell syntax as well. Here’s the same find | wc command implemented with the spawn function:

const child = spawn('find . -type f | wc -l', { stdio: 'inherit', shell: true });

Because of the stdio: 'inherit' option above, when we execute the code, the child process inherits the main process stdin, stdout, and stderr. This causes the child process data events handlers to be triggered on the main process.stdout stream, making the script output the result right away.

Because of the shell: true option above, we were able to use the shell syntax in the passed command, just like we did with exec. But with this code, we still get the advantage of the streaming of data that the spawn function gives us. This is really the best of both worlds.

There are a few other good options we can use in the last argument to the child_process functions besides shell and stdio. We can, for example, use the cwd option to change the working directory of the script. For example, here’s the same count-all-files example done with a spawn function using a shell and with a working directory set to my Downloads folder. The cwd option here will make the script count all files I have in ~/Downloads:

const child = spawn('find . -type f | wc -l', { stdio: 'inherit', shell: true, cwd: '/Users/samer/Downloads' });

Another option we can use is the env option to specify the environment variables that will be visible to the new child process. The default for this option is process.env which gives any command access to the current process environment. If we want to override that behavior, we can simply pass an empty object as the env option or new values there to be considered as the only environment variables:

const child = spawn('echo $ANSWER', { stdio: 'inherit', shell: true, env: { ANSWER: 42 }, });

The echo command above does not have access to the parent process’s environment variables. It can’t, for example, access $HOME, but it can access $ANSWER because it was passed as a custom environment variable through the env option.

One last important child process option to explain here is the detached option, which makes the child process run independently of its parent process.

Assuming we have a file timer.js that keeps the event loop busy:

setTimeout(() => { // keep the event loop busy }, 20000);

We can execute it in the background using the detached option:

const { spawn } = require('child_process'); const child = spawn('node', ['timer.js'], { detached: true, stdio: 'ignore' }); child.unref();

The exact behavior of detached child processes depends on the OS. On Windows, the detached child process will have its own console window while on Linux the detached child process will be made the leader of a new process group and session.

If the unref function is called on the detached process, the parent process can exit independently of the child. This can be useful if the child is executing a long-running process, but to keep it running in the background the child’s stdio configurations also have to be independent of the parent.

The example above will run a node script (timer.js) in the background by detaching and also ignoring its parent stdio file descriptors so that the parent can terminate while the child keeps running in the background.

The execFile function

If you need to execute a file without using a shell, the execFile function is what you need. It behaves exactly like the exec function, but does not use a shell, which makes it a bit more efficient. On Windows, some files cannot be executed on their own, like .bat or .cmd files. Those files cannot be executed with execFile and either exec or spawn with shell set to true is required to execute them.

The *Sync function

The functions spawn, exec, and execFile from the child_process module also have synchronous blocking versions that will wait until the child process exits.

const { spawnSync, execSync, execFileSync, } = require('child_process');

Those synchronous versions are potentially useful when trying to simplify scripting tasks or any startup processing tasks, but they should be avoided otherwise.

The fork() function

The fork function is a variation of the spawn function for spawning node processes. The biggest difference between spawn and fork is that a communication channel is established to the child process when using fork, so we can use the send function on the forked process along with the global process object itself to exchange messages between the parent and forked processes. We do this through the EventEmitter module interface. Here’s an example:

The parent file, parent.js:

const { fork } = require('child_process'); const forked = fork('child.js'); forked.on('message', (msg) => { console.log('Message from child', msg); }); forked.send({ hello: 'world' });

The child file, child.js:

process.on('message', (msg) => { console.log('Message from parent:', msg); }); let counter = 0; setInterval(() => { process.send({ counter: counter++ }); }, 1000);

In the parent file above, we fork child.js (which will execute the file with the node command) and then we listen for the message event. The message event will be emitted whenever the child uses process.send, which we’re doing every second.

To pass down messages from the parent to the child, we can execute the send function on the forked object itself, and then, in the child script, we can listen to the message event on the global process object.

When executing the parent.js file above, it’ll first send down the { hello: 'world' } object to be printed by the forked child process and then the forked child process will send an incremented counter value every second to be printed by the parent process.

Let’s do a more practical example about the fork function.

Let’s say we have an http server that handles two endpoints. One of these endpoints (/compute below) is computationally expensive and will take a few seconds to complete. We can use a long for loop to simulate that:

const http = require('http'); const longComputation = () => { let sum = 0; for (let i = 0; i  { if (req.url === '/compute') { const sum = longComputation(); return res.end(`Sum is ${sum}`); } else { res.end('Ok') } }); server.listen(3000);

This program has a big problem; when the the /compute endpoint is requested, the server will not be able to handle any other requests because the event loop is busy with the long for loop operation.

There are a few ways with which we can solve this problem depending on the nature of the long operation but one solution that works for all operations is to just move the computational operation into another process using fork.

We first move the whole longComputation function into its own file and make it invoke that function when instructed via a message from the main process:

In a new compute.js file:

const longComputation = () => { let sum = 0; for (let i = 0; i  { const sum = longComputation(); process.send(sum); });

Now, instead of doing the long operation in the main process event loop, we can fork the compute.js file and use the messages interface to communicate messages between the server and the forked process.

const http = require('http'); const { fork } = require('child_process'); const server = http.createServer(); server.on('request', (req, res) => { if (req.url === '/compute') { const compute = fork('compute.js'); compute.send('start'); compute.on('message', sum => { res.end(`Sum is ${sum}`); }); } else { res.end('Ok') } }); server.listen(3000);

When a request to /compute happens now with the above code, we simply send a message to the forked process to start executing the long operation. The main process’s event loop will not be blocked.

Once the forked process is done with that long operation, it can send its result back to the parent process using process.send.

In the parent process, we listen to the message event on the forked child process itself. When we get that event, we’ll have a sum value ready for us to send to the requesting user over http.

The code above is, of course, limited by the number of processes we can fork, but when we execute it and request the long computation endpoint over http, the main server is not blocked at all and can take further requests.

Node’s cluster module, which is the topic of my next article, is based on this idea of child process forking and load balancing the requests among the many forks that we can create on any system.

That’s all I have for this topic. Thanks for reading! Until next time!

Learning React or Node? Checkout my books:

  • Learn React.js by Building Games
  • Node.js Beyond the Basics