Dječji procesi Node.js: sve što trebate znati

Kako koristiti spawn (), exec (), execFile () i fork ()

Ažuriranje: Ovaj je članak sada dio moje knjige "Node.js izvan osnova".

Pročitajte ažuriranu verziju ovog sadržaja i više o Nodeu na jscomplete.com/node-beyond-basics .

Izvedba s jednim navojem, koja ne blokira, u Node.js izvrsno funkcionira za jedan postupak. Ali na kraju, jedan proces u jednom CPU-u neće biti dovoljan da podnese sve veće opterećenje vaše aplikacije.

Bez obzira koliko moćan bio vaš poslužitelj, jedna nit može podržati samo ograničeno opterećenje.

Činjenica da se Node.js izvodi u jednoj niti ne znači da ne možemo iskoristiti više procesa i, naravno, više strojeva.

Korištenje više procesa najbolji je način za skaliranje aplikacije Node. Node.js je dizajniran za izgradnju distribuiranih aplikacija s mnogo čvorova. Zbog toga se zove Node . Skalabilnost je ugrađena u platformu i to nije nešto o čemu ćete početi razmišljati kasnije tijekom života aplikacije.

Ovaj je članak opis dijela mog tečaja Pluralsight o Node.js. Tamo pokrivam sličan sadržaj u video formatu.

Napominjemo da će vam trebati dobro razumijevanje događaja i streamova Node.js prije nego što pročitate ovaj članak. Ako već niste, preporučujem vam da pročitate ova dva druga članka prije nego što pročitate ovaj:

Razumijevanje Node.js arhitekture vođene događajima

Većina objekata Nodea - poput HTTP zahtjeva, odgovora i streamova - implementiraju modul EventEmitter kako bi mogli ...

Potoci: Sve što trebate znati

Streamovi Node.js imaju reputaciju da je s njima teško raditi, a još ih je teže razumjeti. Pa, imam dobre vijesti ...

Modul za dječje procese

Podređeni proces možemo lako vrtjeti pomoću Node-ovog child_processmodula i ti podređeni procesi mogu lako međusobno komunicirati sustavom za razmjenu poruka.

child_processModul omogućuje nam pristup Operating System funkcionalnosti pokretanjem bilo koju naredbu sustava unutar, dobro, proces dijete.

Možemo kontrolirati taj podređeni ulazni tok procesa i preslušati njegov izlazni tok. Također možemo kontrolirati argumente koji će se prosljeđivati ​​osnovnoj naredbi OS-a i možemo raditi sve što želimo s rezultatima te naredbe. Na primjer, izlaz jedne naredbe možemo usmjeriti kao ulaz u drugu (baš kao što to činimo u Linuxu) jer nam se svi ulazi i izlazi tih naredbi mogu predstaviti pomoću Node.js streamova.

Primijetite da su primjeri koje ću koristiti u ovom članku svi zasnovani na Linuxu. U sustavu Windows trebate zamijeniti naredbe koje koristim s njihovim Windows mogućnostima.

Postoje četiri različita načina za stvaranje proces djece u čvor: spawn(), fork(), exec(), i execFile().

Vidjet ćemo razlike između ove četiri funkcije i kada ih koristiti.

Izrođeni dječji procesi

spawnFunkcija pokreće naredbu u novom postupku i možemo ga koristiti da prođe tu naredbu argumente. Na primjer, ovdje je kod za stvaranje novog procesa koji će izvršiti pwdnaredbu.

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

Jednostavno destrukturiramo spawnfunkciju iz child_processmodula i izvršavamo je s naredbom OS kao prvim argumentom.

Rezultat izvršavanja spawnfunkcije (gornji childobjekt) je ChildProcessinstanca koja implementira EventEmitter API. To znači da obrađivače događaja za ovaj podređeni objekt možemo registrirati izravno. Na primjer, možemo nešto učiniti kada se podređeni proces izlazi registracijom voditelja za exitdogađaj:

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

Gornji vodič daje nam izlaz codeza podređeni proces i signal, ako postoji, koji je korišten za prekid podređenog postupka. Ova je signalvarijabla nula kada podređeni proces izlazi normalno.

Ostali događaji koje možemo registrirati rukuju za sa a ChildProcessslučajevi su disconnect, error, close, i message.

  • disconnectDogađaj se emitira kada roditelj proces ručno poziva child.disconnectfunkcije.
  • errorDogađaj emitira, ako se proces ne može biti iznjedrio ili ubijen.
  • closeDogađaj se emitira kada stdiopotoci proces dijete dobiti zatvoreni.
  • messageDogađaj je najvažniji. Emitira se kada podređeni proces koristi process.send()funkciju za slanje poruka. Tako roditelji / dijete mogu komunicirati međusobno. Primjer toga vidjet ćemo u nastavku.

Svaki proces dijete dobiva tri standardne stdiopotoci, koji možemo pristupiti pomoću child.stdin, child.stdouti child.stderr.

Kad se ti potoci zatvore, podređeni proces koji ih je koristio emitirat će closedogađaj. Ovaj se closedogađaj razlikuje od exitdogađaja jer više podređenih procesa može dijeliti iste stdiostreamove, pa jedan podređeni proces koji izlazi ne znači da su se tokovi zatvorili.

Budući da su svi tokovi odašiljači događaja, možemo slušati različite događaje na onim stdiotijekovima koji su pridruženi svakom podređenom procesu. Za razliku od uobičajenog postupka, u podređenom procesu stdout/ stderrstreamovi su čitljivi tokovi, dok je stdinstream moguće zapisati. To je u osnovi obrnuto od onih vrsta koje se nalaze u glavnom procesu. Događaji koje možemo koristiti za te streamove standardni su. Najvažnije je da na čitljivim streamovima možemo preslušati datadogađaj koji će imati izlaz naredbe ili bilo kakvu pogrešku koja se dogodi tijekom izvršavanja naredbe:

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

Gore navedena dva obrađivača prijavit će oba slučaja u glavni postupak stdouti stderr. Kada izvršimo spawngornju funkciju, izlaz pwdnaredbe se ispisuje i podređeni proces izlazi s kodom 0, što znači da nije došlo do pogreške.

Možemo proslijediti argumente naredbi koju spawnfunkcija izvršava pomoću drugog argumenta spawnfunkcije, koji je niz svih argumenata koji se prosljeđuju naredbi. Na primjer, za izvršavanje findnaredbe na trenutnom direktorijumu s -type fargumentom (samo za popis datoteka) možemo učiniti:

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

Ako se tijekom izvršenja naredbe dogodi pogreška, na primjer, ako damo gore pronaći nevaljano odredište, child.stderrdatapokretač događaja će se aktivirati, a exitobrađivač događaja prijavit će izlazni kod 1, što znači da je došlo do pogreške. Vrijednosti pogreške zapravo ovise o glavnom OS-u i vrsti pogreške.

Dijete proces stdinje tok za pisanje. Možemo ga koristiti za slanje naredbe nekom unosu. Baš kao i bilo koji zapisljiv zapis, najlakši način za njegovu upotrebu je upotreba pipefunkcije. Čitljivi tok jednostavno preusmjerimo u zapisljiv tok. Budući da je glavni proces stdinčitljiv tok, možemo ga usmjeriti u podređeni stdintok procesa . Na primjer:

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