Node.js › CLI Tools & Scripting with Node.js
How do you write cross-platform shell scripts in Node.js that work identically on Windows, macOS, and Linux?
IntermediateAnswer
Rather than relying on OS-specific shell commands or path separators, cross-platform Node.js scripts use Node's built-in modules (fs, path) instead of shelling out to 'rm', 'cp', or 'mkdir', use path.join()/path.sep instead of hardcoded slashes, and when shelling out to external commands is genuinely necessary, use a cross-platform library like shelljs or execa that normalizes command behavior across operating systems, since raw shell commands like 'rm -rf' simply don't exist on Windows by default.
// Fragile: relies on a Unix-only shell command
// exec('rm -rf dist');
// Cross-platform: use Node's own fs API instead
const fs = require('node:fs/promises');
await fs.rm('dist', { recursive: true, force: true });Real-world example A build script that previously called 'rm -rf dist && cp -r src dist' via exec() (breaking on Windows CI runners) is rewritten using fs.rm() and fs.cp() directly from Node's fs/promises module, working identically across the team's mixed Windows, macOS, and Linux development machines.