Node.jsQuestion 14 of 26
fork vs spawn
Answer out loud or in your head first, then compare.
Answer
Both create a child process. spawn runs any program, and fork is specialised for running a Node module with an IPC communication channel.
JavaScript
import { spawn, fork } from 'node:child_process';
const processA = spawn(process.execPath, ['--version']);
processA.stdout.on('data', chunk => console.log(chunk.toString()));
processA.on('error', console.error);
// Requires an existing worker.js file
const worker = fork('./worker.js');
worker.on('error', console.error);
worker.send({ task: 'report' });Pitfall: fork() in Node doesn't clone the process memory like the Unix syscall of the same name. The processes have their own memory. For cooperation within one process there are worker threads, among other options.
How did it go? Be honest — “Not yet” puts the question on your review list.