The bin field and npx

A package can ship a command as well as a module. The bin field maps a name a reader types to a file in the package, npm writes a link with that name into node_modules/.bin, and the folder is already on the PATH of every script of package.json.

The lesson builds a small word counter, installs it from a folder of the same project and runs it three ways: by its path, by the link and through npx. The three exit codes of the tool are the last section, because a command that a script calls is only as useful as its status.

The bin field

The package lives in tools/wc-cli and has three fields that make it a command: a name, a version and bin. The value is an object because a package can ship several commands, each under its own name; a single command may also be written as a plain string.

The file itself starts with a shebang, the two characters and a word that tell the operating system which program has to read the rest. Without it the run goes to the shell, which does not know console.log.

The file tools/wc-cli/package.json:

{ "name": "wc-cli", "version": "1.0.0", "type": "commonjs", "bin": { "wc-cli": "./cli.js" }, "files": [ "cli.js" ] }

The file tools/wc-cli/cli.js:

#!/usr/bin/env node const { readFileSync } = require('node:fs'); const file = process.argv[2]; if (file === undefined) { console.error('usage: wc-cli <file>'); process.exitCode = 2; } else { try { const text = readFileSync(file, 'utf8'); const lines = text.split('\n').filter((line, index, all) => index < all.length - 1 || line !== '').length; const words = text.split(/\s+/).filter((word) => word !== '').length; console.log(lines + ' ' + words + ' ' + file); } catch (error) { console.error('wc-cli: ' + error.code + ' ' + file); process.exitCode = 1; } }

The tool prints the three numbers that wc prints first: the lines, the words and the name of the file. The filter on the lines drops the empty last entry that a trailing newline leaves in the split, and the words are the runs of anything that is not whitespace.

node tools/wc-cli/cli.js notes.txt
echo "the exit status: $?"

3 11 notes.txt
the exit status: 0

A path works from anywhere and is what a program inside the package would use. The command is not a command yet: the shell has to be told the path, and the file has to be found before it can run.

The link in node_modules/.bin

A folder can be a dependency like a registry package: npm install ./tools/wc-cli writes file:tools/wc-cli into the manifest and links the folder into node_modules instead of copying it, so an edit in the tool is an edit in the installed package. The bin field then becomes a link of its own.

npm install ./tools/wc-cli
cat package.json

{ "name": "cli-course", "version": "1.0.0", "type": "commonjs", "dependencies": { "wc-cli": "file:tools/wc-cli" } }

The installed command is a symbolic link named after the key of the bin object. The program prints where it points, which is the second half of the mapping: the name in the manifest, the file in the package.

The file link.js:

const { readlinkSync } = require('node:fs'); console.log('the link points at:', readlinkSync('node_modules/.bin/wc-cli'));

node link.js
node_modules/.bin/wc-cli notes.txt

the link points at: ../wc-cli/cli.js
3 11 notes.txt

The link is relative, which keeps a copied node_modules working, and it sits in a folder that npm adds to the PATH of a script. On Windows npm writes three small scripts instead of the link, and the call is the same.

npx

npx runs a command from node_modules/.bin with the arguments after the name, so the path does not have to be typed and a script does not have to exist. --no-install makes it use only what the folder already has, which is the form to put in a lesson, a test and any command a pipeline repeats.

npx --no-install wc-cli notes.txt

3 11 notes.txt

Without the flag npx is a small installer as well: a name that no folder has is downloaded into a cache and run from there. That is convenient at a terminal and wrong in a script, where the version that runs has to be the version of the lock file.

The exit status of a tool

A command line tool reports through its status, and the three codes below are the convention that the shell and every script around it assume: 0 for success, 1 for a failure of the work and 2 for a wrong call. The program sets process.exitCode and returns, which lets Node.js finish the pending output before it exits.

npx --no-install wc-cli
echo "the exit status: $?"
npx --no-install wc-cli missing.txt
echo "the exit status: $?"

usage: wc-cli <file>
the exit status: 2
wc-cli: ENOENT missing.txt
the exit status: 1

The two messages went to stderr, which is why they appear before the status of the shell rather than mixed with the output of the tool. ENOENT is the code that the file system gives for a path that does not exist, and the tool passes it on in a message of its own instead of printing a stack. A caller can now tell a wrong call from a missing file without reading the text.

The next lesson packs the tool into a tarball and shows which files of the folder go into it, which is the last piece between this command and a package that another machine can install.

Exercises

  1. Remove the shebang and run the tool through the link. Which program tries to read the file, and what does the error say?
  2. Add a second command to the bin object and install the folder again. Which two links appear in the folder, and what does each run?
  3. Run npx wc-cli with a name that no package has and no network. Which message comes back, and which flag avoids the whole situation?
  4. Count the words of a file with no trailing newline and one with two blank lines at the end. Which number changes, and which expression in the program is responsible?
  5. Make the tool exit with 2 for a missing file instead of 1. Which caller of the tool could tell the two cases apart, and which one could not?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does the bin field of a package do?

    Answer

    It maps a command name to a file of the package

    npm writes a link with that name into node_modules/.bin, and the link runs the file.

  2. What does this program print? const bin = { "wc-cli": "./cli.js", "wc-count": "./count.js" }; console.log(Object.keys(bin).join(" "));

    Answer

    wc-cli wc-count

    The keys are the command names and they keep the order of the object.

  3. What is the first line of a file that ships a command?

    Answer

    A shebang that names the runtime

    The shebang tells the operating system which program reads the rest of the file.

  4. What does this program print? const path = "node_modules/.bin/wc-cli"; console.log(path.split("/").pop(), path.startsWith("node_modules"));

    Answer

    wc-cli true

    The last part of the path is the command name and the folder prefix matches.

  5. Where does npm put the link of a bin entry?

    Answer

    In node_modules/.bin

    The folder belongs to the project and is on the PATH of its scripts.

  6. What does this program print? const args = ["notes.txt", "--verbose"]; console.log(args[0], args.length);

    Answer

    notes.txt 2

    The first argument is the file and the array has two entries.

  7. What does npx --no-install refuse to do?

    Answer

    Download a package that the project does not have

    The flag limits npx to the folder, which keeps a script on the versions of the lock file.

  8. What does this program print? const codes = { ok: 0, failure: 1, usage: 2 }; console.log(codes.usage > codes.failure, codes.ok === 0);

    Answer

    true true

    The usage code is the greater of the two, and the success code is zero.

  9. Which stream carries the usage message of the tool?

    Answer

    stderr, because it is a message about the call and not its result

    The result of a command goes to stdout, and a diagnostic goes to stderr so a pipe can keep them apart.

  10. What does this program print? const text = "a b\nc\n"; console.log(text.split(/\s+/).filter((word) => word !== "").length);

    Answer

    3

    The three words are separated by the space and the two newlines, and the empty entry at the end is dropped.

The programs and commands on this page were run with Node.js 24.22.1 and npm 11.12.1, and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image