Skip to content
jshacks.dev
Node.js

How to Write a Node.js Script That Works on Windows, macOS and Linux

Write a Node.js script that runs on Windows, macOS and Linux: build paths with path, find home and temp folders, avoid shell commands and spawn programs safely.

7 min read
Summarize in AI
Flat illustration of a terminal session, with the Node.js, Linux and GNU Bash logos.

A script that works on your laptop and fails on a teammate's machine almost never fails because of JavaScript. It fails at the edges where Node.js touches the operating system: a path with a backslash, a shell command that only exists on Unix, a line ending that sneaks into a comparison, a file name that differs only by case. The language is identical on Windows, macOS and Linux. The environment is not. This post collects the habits that keep a Node.js 26 script portable: build paths with node:path, ask node:os for folders instead of hard-coding them, use fs instead of shell commands, run other programs without a shell where you can, and test the awkward cases on the platform that will bite you. Each example prints what it would print on the platform it names.

Never join paths with a slash

The most common portability bug is a string like "data/" + name. Windows accepts forward slashes in many APIs, so it often works until it does not, for instance when the path is printed, compared or passed to another program. Use path.join, which uses the separator of the current platform.

join.mjsJavaScript
import path from "node:path";

const file = path.join("data", "exports", "report.csv");
console.log(file);
console.log(path.sep);

On Linux and macOS:

Text
data/exports/report.csv
/

On Windows:

Text
data\exports\report.csv
\

Use path.join to combine segments and path.resolve to turn them into an absolute path. Do not use path.join for URLs, because a URL always uses forward slashes. For those use the URL class or path.posix.join.

posix.mjsJavaScript
import path from "node:path";

console.log(path.posix.join("assets", "img", "logo.png"));
console.log(path.win32.join("assets", "img", "logo.png"));
Text
assets/img/logo.png
assets\img\logo.png

Both path.posix and path.win32 exist on every platform, so you can also test your path logic for the other system without owning one. Nothing is read from disk, which makes it safe to run anywhere.

Find files relative to the script, not the terminal

A script that opens ./config.json depends on the directory the user was in when they ran it. The reliable anchor is the script's own location. In an ES module, import.meta.dirname (Node.js 20.11 and later) gives the folder, and import.meta.filename the file.

anchor.mjsJavaScript
import path from "node:path";
import { readFile } from "node:fs/promises";

const configPath = path.join(import.meta.dirname, "config.json");
const config = JSON.parse(await readFile(configPath, "utf8"));
console.log(config.name);

If config.json contains { "name": "builder" }, this prints:

Text
builder

In older ES module code you may see fileURLToPath(import.meta.url) instead. The trap to avoid is new URL(import.meta.url).pathname, which returns /C:/work/script.mjs on Windows, with a leading slash that fs rejects. fileURLToPath and import.meta.dirname handle drive letters properly.

Ask the system for well-known folders

Hard-coded /tmp and /home/me paths are Linux assumptions. node:os knows the right answer for each platform.

folders.mjsJavaScript
import os from "node:os";
import path from "node:path";

console.log(os.platform());
console.log(path.basename(os.homedir()) === os.userInfo().username);
console.log(typeof os.tmpdir());
Text
linux
true
string

On macOS the first line is darwin and on Windows it is win32, whatever the CPU width, so a 64-bit Windows machine still says win32. The environment variables differ too: HOME is set on Unix, while Windows uses USERPROFILE. Do not read either one directly. os.homedir() consults the right source for each system, and os.tmpdir() returns the temp folder, which is /tmp on Linux, a per-user folder under /var/folders on macOS, and a folder inside AppData on Windows.

For temporary working space use fs.mkdtemp, which creates a unique directory and returns its path.

tmp.mjsJavaScript
import { mkdtemp, writeFile, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";

const dir = await mkdtemp(path.join(os.tmpdir(), "build-"));
await writeFile(path.join(dir, "out.txt"), "ok");
console.log(path.basename(dir).startsWith("build-"));
await rm(dir, { recursive: true, force: true });
Text
true

Do file work in Node.js, not in the shell

A script that calls exec("rm -rf dist") or exec("cp -r a b") works on macOS and Linux and fails on Windows, where those commands do not exist in cmd.exe. Every common file operation has a Node.js function that behaves the same on all three.

Shell habitPortable Node.js call
rm -rf distfs.rm("dist", { recursive: true, force: true })
mkdir -p a/bfs.mkdir("a/b", { recursive: true })
cp -r src outfs.cp("src", "out", { recursive: true })
mv a bfs.rename("a", "b")
cat filefs.readFile("file", "utf8")
clean.mjsJavaScript
import { rm, mkdir, cp, readdir } from "node:fs/promises";

await rm("dist", { recursive: true, force: true });
await mkdir("dist/assets", { recursive: true });
await cp("static", "dist/assets", { recursive: true });

console.log(await readdir("dist/assets"));

If static holds logo.svg and app.css, the result is (sorted for display):

Text
[ 'app.css', 'logo.svg' ]

The force: true option makes rm ignore a missing path, which is what -f does. readdir order is not guaranteed on every platform, so sort before you compare. For the same reason, rename cannot move a file across drives on Windows, and fails with EXDEV. When the source and target may sit on different volumes, copy and then delete.

Run other programs without a shell

Sometimes you must call another program, such as git or tsc. Use execFile or spawn and pass the arguments as an array. There is no shell to interpret quotes, so there is nothing to quote differently on Windows, and no injection risk from file names that contain spaces or ;.

run-git.mjsJavaScript
import { execFile } from "node:child_process";
import { promisify } from "node:util";

const run = promisify(execFile);
const { stdout } = await run("git", ["--version"]);
console.log(stdout.startsWith("git version"));
Text
true

There is one Windows wrinkle. Programs installed through npm, such as npm, npx, tsc and eslint, are .cmd files on Windows. Since the security fixes released in April 2024 (Node.js 18.20.2, 20.12.2 and 21.7.3, in every later release), spawning a .cmd or .bat file without shell: true throws EINVAL. The portable pattern is to run Node.js itself on the tool's entry file, or to call the package manager through process.execPath, or to use shell: true only for a command you wrote yourself and never for user input.

run-node-tool.mjsJavaScript
import { execFile } from "node:child_process";
import { promisify } from "node:util";

const run = promisify(execFile);
const { stdout } = await run(process.execPath, ["--version"]);
console.log(stdout.trim().startsWith("v"));
Text
true

process.execPath is the exact node binary running your script, so a child process uses the same version.

Line endings, case and other quiet differences

Windows files often end lines with \r\n, Unix files with \n. Splitting a file on "\n" leaves a trailing \r on every line when the file came from Windows, and a comparison like line === "ok" silently fails.

lines.mjsJavaScript
const text = "alpha\r\nbeta\r\n";

console.log(text.split("\n"));
console.log(text.split(/\r?\n/));
Text
[ 'alpha\r', 'beta\r', '' ]
[ 'alpha', 'beta', '' ]

Use /\r?\n/ when you read files you did not write, and os.EOL only when you write a file for a human on the current machine. For files that are committed to Git, prefer \n everywhere and let a .gitattributes rule handle conversion.

Case matters differently. Linux file systems are case sensitive, so Readme.md and README.md are different files. macOS and Windows are usually case insensitive but case preserving, so an import "./Utils.js" that points at utils.js works on a laptop and breaks in a Linux CI container. Match the case exactly, and run CI on Linux so the mistake is caught before a release.

Two more traps are worth a line each. Windows reserves names such as CON, NUL and COM1, and forbids characters like : and ? in file names, so do not build file names from raw user text. And fs.chmod and the executable bit mostly do nothing on Windows, so a script that depends on 0o755 should set its mode in the package.json bin field and let npm handle it.

Environment variables in npm scripts

A package.json script such as "build": "NODE_ENV=production tsc" fails on Windows cmd.exe, because the VAR=value command form is Unix shell syntax. Two portable answers exist. Put the setting in code, reading process.env.NODE_ENV ?? "development". Or keep the script free of shell features and load variables with Node.js itself through node --env-file=.env script.mjs, which reads the same file on every platform.

env.mjsJavaScript
const mode = process.env.NODE_ENV ?? "development";
console.log(`mode: ${mode}`);

Run with node --env-file=.env env.mjs and a .env containing NODE_ENV=production:

Text
mode: production

Test the platform you do not use

You cannot reason your way out of every difference, so run the script where it will live. A GitHub Actions matrix over ubuntu-latest, macos-latest and windows-latest costs a few lines and finds nearly every issue above. The [Node.js path documentation](https://nodejs.org/api/path.html) describes the posix and win32 variants in detail, and it is worth ten minutes the first time you write a tool other people will install.

Taggedbeginner
Share

Keep reading

Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, JavaScript, Apache Kafka, Redis and RabbitMQ logos.
Node.js

The Node.js Event Loop Phases Explained

Learn the six phases of the Node.js event loop, where timers, I/O, setImmediate, process.nextTick and promises run, and why their order sometimes surprises you.

6 min read
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, RabbitMQ, Apache Kafka, Redis and npm logos.
Node.js

What Is Node.js, and What Is It Good At?

Node.js runs JavaScript outside the browser on the V8 engine. Learn what it is, how its event loop works, where it shines, and where another tool fits better.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.