TCP Networking with net and Running Child Processes
Go below HTTP with node:net: TCP servers and clients, sockets as duplex streams, framing a line-based protocol, then run other programs from Node with execFile, spawn, exec and fork, including options, exit codes, streaming I/O, IPC messages and avoiding shell injection.
kvi5hnuCode Sprout team member7 min readOn this page
HTTP is one protocol among many. Databases, caches, mail servers and game servers speak their own protocols directly over TCP, and Node's node:net module lets you write both sides. The second half of this article covers node:child_process, which runs other programs from Node: compilers, git, image converters or more Node processes.
TCP servers and clients
A TCP connection is a reliable, ordered, two-way stream of bytes between two programs. In Node, each connection is a net.Socket, which is a Duplex stream (article 126): you write to send data and read to receive it.
net.createServer((socket) => ...)calls your function once per client connection;server.listen(port)starts it.net.connect(port, host)(also callednet.createConnection) opens a client socket.socket.end(data?)sends any final data and closes your side;socket.destroy()closes immediately. Thecloseevent fires when the connection is fully closed.- Add an
errorlistener on every socket. Clients disconnect abruptly all the time (ECONNRESET), and without a listener, that would crash the server (article 125).
TCP has no notion of messages: one write on one side may arrive as two chunks, or two writes as one chunk. A protocol needs framing to mark where each message ends. The simplest framing is one message per line, which readline handles. Other options are length prefixes (a 4-byte size before each message, article 124) or delimiters such as \0.
const net = require("node:net");
const readline = require("node:readline");
const { once } = require("node:events");
// A tiny line-based key-value server: "SET key value", "GET key", "QUIT"
const store = new Map();
const server = net.createServer(async (socket) => { // one call per client connection
socket.setEncoding("utf8");
socket.on("error", () => {}); // a client vanishing must not crash us
socket.write("READY\n");
for await (const line of readline.createInterface({ input: socket })) {
const [cmd, key, ...rest] = line.trim().split(" ");
if (cmd === "SET" && key) {
store.set(key, rest.join(" "));
socket.write("OK\n");
} else if (cmd === "GET" && key) {
socket.write(store.has(key) ? `VALUE ${store.get(key)}\n` : "NOT_FOUND\n");
} else if (cmd === "QUIT") {
socket.end("BYE\n"); // send, then close our side
return;
} else {
socket.write("ERROR unknown command\n");
}
}
});
// A client: send each command, wait for one reply line
async function client(port, commands) {
const socket = net.connect(port, "localhost");
socket.setEncoding("utf8");
const replies = readline.createInterface({ input: socket })[Symbol.asyncIterator]();
console.log("server:", (await replies.next()).value);
for (const cmd of commands) {
socket.write(cmd + "\n");
console.log(`${cmd.padEnd(24)} -> ${(await replies.next()).value}`);
}
await once(socket, "close");
}
async function main() {
server.listen(0);
await once(server, "listening");
await client(server.address().port, ["SET greeting hello world", "GET greeting", "GET missing", "DELETE x", "QUIT"]);
server.close();
}
main();
server: READY
SET greeting hello world -> OK
GET greeting -> VALUE hello world
GET missing -> NOT_FOUND
DELETE x -> ERROR unknown command
QUIT -> BYE
The server handles every client concurrently on one thread: each connection's for await loop simply waits while that client is idle. The client takes the async iterator of reply lines and calls next() once per command, matching the protocol's one-reply-per-request rule. You could also talk to this server by hand with nc localhost <port> (netcat).
Related modules:
node:tlsis the encrypted version ofnet, just ashttpsis the encrypted version ofhttp.node:dgramprovides UDP: individual datagrams, with no connection and no delivery guarantee.netservers can also listen on a Unix domain socket (a file path) or a Windows named pipe for fast communication between processes on the same machine.
Running other programs
The node:child_process module starts child processes. Each runs independently, possibly on another CPU core, and communicates with your program through its standard input and output streams, its exit code, and for Node children, a message channel.

const { execFile, execFileSync, spawn } = require("node:child_process");
const { promisify } = require("node:util");
const { once } = require("node:events");
const readline = require("node:readline");
const execFileP = promisify(execFile);
// process.execPath is the running node binary: a program we know exists everywhere
const NODE = process.execPath;
async function main() {
// 1. Run a program to completion, collecting its output (no shell involved)
const out = execFileSync(NODE, ["-p", "6 * 7"], { encoding: "utf8" });
console.log("execFileSync:", out.trim());
// 2. The same, asynchronously; several can run in parallel
const results = await Promise.all(
["1 + 1", "'ab'.repeat(2)", "process.argv.length"].map((expr) =>
execFileP(NODE, ["-p", expr], { encoding: "utf8", timeout: 5000 })),
);
console.log("parallel:", results.map((r) => r.stdout.trim()));
// A nonzero exit code rejects; the error carries code, stdout and stderr
try {
await execFileP(NODE, ["-e", "console.error('bad input'); process.exit(3)"]);
} catch (err) {
console.log("failed:", err.code, JSON.stringify(err.stderr.trim()));
}
// 3. spawn: stream input and output while the child runs
const child = spawn(NODE, ["-e", `
process.stdin.setEncoding("utf8");
process.stdin.on("data", (d) => process.stdout.write(d.toUpperCase()));
`]);
// Output chunks don't match writes, so split the output stream into lines
readline.createInterface({ input: child.stdout }).on("line", (line) => console.log("child says:", line));
child.stdin.write("hello\n");
setTimeout(() => {
child.stdin.write("bye\n");
child.stdin.end(); // end of input: the child's stdin closes
}, 50);
const [code, signal] = await once(child, "close");
console.log("child exited:", code, signal);
}
main();
execFileSync: 42
parallel: [ '2', 'abab', '1' ]
failed: 3 "bad input"
child says: HELLO
child says: BYE
child exited: 0 null
execFile and execFileSync
execFile(file, args, options, callback) runs a program and collects all of its output, calling back with (err, stdout, stderr) when it exits. The promisified version resolves to { stdout, stderr } and rejects if the program fails; the error has code (the exit code), signal, stdout and stderr. execFileSync blocks and returns stdout, which is fine in scripts. Several execFile calls can run in parallel with Promise.all.
Useful options include cwd (working directory), env (environment; the default is process.env), encoding ("utf8" to get strings instead of Buffers), timeout (kill the child after that many milliseconds), maxBuffer (maximum output collected; the child is killed beyond it, default 1 MB), input (stdin data, Sync functions only) and signal (an AbortSignal to cancel).
exec and the shell
exec(command) and execSync(command) run a string through a shell (/bin/sh, or cmd.exe on Windows), so they support pipes, wildcards and redirection: exec("ls *.log | wc -l"). That convenience is dangerous: if any part of the string comes from a user, they can inject commands. A filename like x; rm -rf ~ passed to exec("convert " + name) runs the second command too.
Avoid the shell for anything with variable input. execFile and spawn take the arguments as an array and pass them directly to the program, so special characters have no meaning. The shell: true option brings the risk back.
spawn
spawn(file, args, options) starts a program and returns a ChildProcess immediately, without collecting output. It has three streams; their direction is the reverse of what they are inside the child:
child.stdinis writable: what you write becomes the child's input. Callend()when you're done, or many programs wait forever for more input.child.stdoutandchild.stderrare readable: the child's output, as it's produced.
Use spawn for long-running processes, large output (which exec would collect in memory up to maxBuffer), and interactive exchanges. The close event reports the exit code, or the signal that ended the process. child.kill(signal?) sends SIGTERM by default, and child.pid is its process ID. With stdio: "inherit", the child uses the parent's terminal directly, which is useful for running build tools from a script.
fork and IPC
fork(modulePath, args) is spawn specialized for Node modules. It runs the module in a new Node process and adds an IPC channel: the parent calls child.send(value) and listens for child.on("message"); the child uses process.send(value) and process.on("message"). Messages are serialized as JSON by default (serialization: "advanced" uses the structured clone algorithm, as in article 120, which also supports Map, Date, typed arrays and BigInt).
const { fork } = require("node:child_process");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
// The child's code: a module that answers messages (normally its own file in your project)
const workerFile = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "fork-")), "fib-worker.js");
fs.writeFileSync(workerFile, `
process.on("message", ({ id, n }) => {
let a = 0n, b = 1n;
for (let i = 0; i < n; i++) [a, b] = [b, a + b]; // CPU work, off the parent's thread
process.send({ id, result: String(a), pid: process.pid });
});
`);
const child = fork(workerFile); // a new Node process with an IPC channel
let pending = 2;
child.on("message", ({ id, result, pid }) => {
console.log(`job ${id}: ${result.length} digits, computed in another process: ${pid !== process.pid}`);
if (--pending === 0) child.disconnect(); // close the channel so the child can exit
});
child.on("exit", (code) => {
console.log("worker exited with", code);
fs.rmSync(path.dirname(workerFile), { recursive: true });
});
child.send({ id: 1, n: 100 });
child.send({ id: 2, n: 1000 });
job 1: 21 digits, computed in another process: true
job 2: 209 digits, computed in another process: true
worker exited with 0
The open IPC channel keeps both processes alive, so the parent calls disconnect() when it's done. A forked process is a whole Node instance, with its own memory and tens of megabytes of overhead, so fork a few long-lived workers rather than one per task. For CPU-bound JavaScript, worker threads (next article) are usually lighter.
Common questions
Why does my spawned process never exit?
Usually the child is waiting for more input on stdin; call child.stdin.end(). With fork, the IPC channel keeps both processes alive until one side calls disconnect() or exits.
Why does exec fail with "maxBuffer length exceeded"?
The program produced more output than maxBuffer. Raise the limit, or better, use spawn and process the output as a stream.
Why does my TCP message arrive in pieces?
TCP is a byte stream, not a message protocol. Frame your messages with line breaks, delimiters or length prefixes, and reassemble them on the receiving side.
Summary
net.createServerandnet.connectgive you TCP sockets, which are Duplex streams. Always handle socket errors, and frame messages because TCP doesn't preserve write boundaries.execFileandexecFileSyncrun a program and collect its output;spawnstreams stdin, stdout and stderr;forkruns a Node module with an IPC message channel.execandexecSyncuse a shell: convenient for pipelines, dangerous with untrusted input. Pass arguments as arrays to avoid shell injection.- Exit codes and signals tell you how a child ended; failures reject with
code,stdoutandstderr.
Practice Questions
Why is this code dangerous, and how do you fix it?
exec(`git log --author=${req.query.author}`);
Answer
The author value goes through a shell, so input like x; cat /etc/passwd runs a second command: shell injection. Pass arguments as an array without a shell:
execFile("git", ["log", `--author=${req.query.author}`]);
A server receives "SET a 1\nGET a\n" in a single data event. What does that show about TCP?
Answer
TCP delivers a stream of bytes without message boundaries, so two writes from the client arrived as one chunk. The server must split the data into messages itself, here by lines.
Which function would you use to run a 10-minute video conversion and show its progress output as it happens?
Answer
spawn, which provides the child's stdout and stderr as streams while it runs. execFile would only return the output after the program exits, and could exceed maxBuffer.
How does a forked child send a result back to its parent?
Answer
With process.send(value). The parent receives it through child.on("message", (value) => ...).
Previous: HTTP in Node: Servers, Routing, Static Files and Clients
Next: Worker Threads in Node: Parallel JavaScript, Messages and Shared Memory

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.