Capstone C: packaging the command
The server of the previous lesson is a development program: it starts, probes itself, prints four answers and stops. What a reader wants is the other half of it, a command that starts the endpoint and stays until Ctrl-C. This lesson splits the two, gives the package a bin entry and packs it.
The split is one function. The handler that the server built inline becomes src/handler.js with a factory that takes the documents, and both the probe and the command call it. The manifest then gains the two fields of a package that ships a command, and the tarball of npm pack --dry-run is the check that the files named in it are the files a reader gets.
The folder holds the copy of project B, the server of the previous lesson, the manifest and the lint config. This lesson adds src/handler.js and bin/search-serve.js, and changes server.js and package.json.
mkdir bin
The handler moves out
A factory that takes the documents and returns a handler is the smallest form that two programs can share. The probe passes its own three documents, the command passes the same three, and a test could pass an empty list. The search object is built inside the factory, so each handler owns one index.
The probe then shrinks to the four requests and the port. It requires the factory, creates the server with the handler and prints what comes back; the route, the JSON and the two errors are one file away.
The file src/handler.js:
vi src/handler.js
const { createSearch } = require('./search');
function send(response, status, body) {
response.writeHead(status, { 'content-type': 'application/json' });
response.end(JSON.stringify(body));
}
function createHandler(documents) {
const search = createSearch(documents);
return function handler(request, response) {
const url = new URL(request.url, 'http://127.0.0.1');
if (url.pathname !== '/search') {
send(response, 404, { error: 'not found', path: url.pathname });
return;
}
const q = url.searchParams.get('q');
if (q === null || q.trim() === '') {
send(response, 400, { error: 'the q parameter is missing or empty' });
return;
}
const results = search.find(q);
send(response, 200, {
query: q,
count: results.length,
hits: results.map((result) => ({ id: result.id, score: result.score })),
});
};
}
module.exports = { createHandler };
The file server.js, which changed:
vi server.js
const { createServer } = require('node:http');
const { DOCUMENTS } = require('./src/index');
const { createHandler } = require('./src/handler');
async function main() {
const server = createServer(createHandler(DOCUMENTS));
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const base = 'http://127.0.0.1:' + server.address().port;
for (const path of ['/search?q=cat+mat', '/search?q=slept', '/search?q=', '/nothing']) {
const answer = await fetch(base + path);
console.log(answer.status + ' ' + path);
console.log(' ' + (await answer.text()));
}
await new Promise((resolve) => server.close(resolve));
console.log('the server is closed');
}
main().catch((error) => {
console.error('error: ' + error.message);
process.exitCode = 1;
});
The probe is not in the package, and that is a decision rather than an accident: the files list below names bin and src, so the tarball holds the command and the library and not the program that tests them. A development script that a reader does not need is weight in the download.
The manifest and the bin field
bin maps a command name to a file of the package, and npm writes a link with that name into node_modules/.bin when the package is installed. main names the module that a require of the package loads, which here is the handler, and files is the whitelist of the tarball.
The three fields are the difference between a folder of code and a package that another machine can install. The lesson on bin and npx covers the link, and the lesson on npm pack covers the whitelist; this lesson is the two together on a real program.
The file package.json:
vi package.json
{
"name": "search-http",
"version": "1.0.0",
"description": "The search index behind an HTTP endpoint",
"type": "commonjs",
"main": "src/handler.js",
"bin": {
"search-serve": "./bin/search-serve.js"
},
"files": [
"bin",
"src"
],
"scripts": {
"test": "node --test --test-reporter=dot",
"lint": "eslint ."
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"eslint": "^10.14.0"
}
}
The description and the three fields are what a reader of the registry page sees, and the two scripts are unchanged. A package that ships a command keeps its tests in the folder and out of the tarball, which is why test is not in the files list.
The command and its statuses
The command reads one optional argument, the port, and starts the server on it. No argument means 8080, --help prints the usage text and returns 0, and anything else is a wrong call with the status 2. The three cases are the ones the tracker of project A ended with, in fewer lines because there is one argument and no file.
The server prints three lines when it is ready: the address, the path of the endpoint and how to stop it. The address comes from server.address().port, so the command reports the port it actually got and not the one it asked for.
The file bin/search-serve.js:
vi bin/search-serve.js
#!/usr/bin/env node
const { createServer } = require('node:http');
const { DOCUMENTS } = require('../src/index');
const { createHandler } = require('../src/handler');
const USAGE = ['usage: search-serve [port]', '', ' port the port to listen on, 8080 by default'].join('\n');
function readOption(argv) {
if (argv.length === 0) {
return { port: 8080 };
}
if (argv[0] === '--help' || argv[0] === '-h') {
return { help: true };
}
const port = Number(argv[0]);
if (argv.length !== 1 || !Number.isInteger(port) || port < 1 || port > 65535) {
return { error: 'the port must be an integer between 1 and 65535' };
}
return { port };
}
function main() {
const option = readOption(process.argv.slice(2));
if (option.help) {
console.log(USAGE);
return;
}
if (option.error !== undefined) {
console.error('error: ' + option.error);
console.error(USAGE);
process.exitCode = 2;
return;
}
const server = createServer(createHandler(DOCUMENTS));
server.listen(option.port, '127.0.0.1', () => {
console.log('listening on http://127.0.0.1:' + server.address().port);
console.log('the endpoint is /search?q=cat+mat');
console.log('press Ctrl-C to stop');
});
process.on('SIGINT', () => {
server.close(() => {
console.log('the server is closed');
});
});
}
main();
The shebang is what makes the link in node_modules/.bin runnable, and the SIGINT handler closes the server so the process can end. Without it, Ctrl-C ends the process at once and a connection in flight is cut; with it, the server stops accepting, answers what it can and then exits.
The first command below prints the usage text, the second one refuses a port that cannot exist, and the third one serves for one second and is stopped by timeout, which is why its status is 124. Without the timeout the prompt would not come back until Ctrl-C, and a page cannot show that.
node bin/search-serve.js --help
echo "the exit status: $?"
node bin/search-serve.js 99999
echo "the exit status: $?"
timeout 1 node bin/search-serve.js 8080
echo "the exit status: $?"
usage: search-serve [port]
port the port to listen on, 8080 by default
the exit status: 0
error: the port must be an integer between 1 and 65535
usage: search-serve [port]
port the port to listen on, 8080 by default
the exit status: 2
listening on http://127.0.0.1:8080
the endpoint is /search?q=cat+mat
press Ctrl-C to stop
the exit status: 124
The usage text of the help and of the wrong call is the same, and the difference is the stream it goes to and the status it leaves. The three lines of the running server are the whole output of a process that answers HTTP requests until something stops it.
npm pack --dry-run
npm pack --dry-run answers what the tarball would hold without writing it. It lists the files with their sizes, the package size, the unpacked size, the shasum and the integrity hash of the archive, and the last line is the name of the file a real pack would write.
npm pack --dry-run
echo "the exit status: $?"
npm notice
npm notice package: search-http@1.0.0
npm notice Tarball Contents
npm notice 1.3kB bin/search-serve.js
npm notice 432B package.json
npm notice 927B src/handler.js
npm notice 1.1kB src/index.js
npm notice 1.1kB src/query.js
npm notice 377B src/search.js
npm notice 296B src/tokenizer.js
npm notice Tarball Details
npm notice name: search-http
npm notice version: 1.0.0
npm notice filename: search-http-1.0.0.tgz
npm notice package size: 2.3 kB
npm notice unpacked size: 5.5 kB
npm notice shasum: 0518520f9f35517a41806f1a8774d69067a44b16
npm notice integrity: sha512-YkJ0fxNzS5qMs[...]SUwYqjaq94kXQ==
npm notice total files: 7
npm notice
search-http-1.0.0.tgz
the exit status: 0
Seven files: the command, the manifest, the handler that the endpoint calls, and the four modules of the search. The test folder and the two development programs are not there, because the files list is a whitelist and only names bin and src. The manifest ships although it is not in the list, which is the fixed rule of the earlier lesson: a package without a manifest cannot be installed.
The shasum is the hash of the tarball, and npm makes it stable by giving every entry the same timestamp, so two packs of the same files on two machines agree. The two sizes are the answer to the question a reader asks first: 2.3 kB over the wire and 5.5 kB unpacked.
npx from the folder
npx runs the command that a package names in its bin field. A dot is the package of the current folder, so npx --yes . takes the folder, puts it in the cache of npx and runs the command from there without an install into the project.
--yes answers the question that npx asks before it fetches something. The command below is the help text through the tarball, which is the closest a reader gets to the experience of the person who installed the package: the same file, run from another folder and with another node_modules.
npx --yes . --help
echo "the exit status: $?"
usage: search-serve [port]
port the port to listen on, 8080 by default
the exit status: 0
The same three lines as the help of the file, which is the proof that the shebang, the bin field and the files list agree. A command that is missing from the tarball fails here and nowhere earlier, which is why the pack is the step before the publish.
Exercises
- Add server.js to the files list and pack again. How many files and how many bytes does the tarball gain?
- Remove the shebang from the command and run it through npx --yes . --help. Which program reads the file, and what does the error say?
- Give the port a default of 3000 instead of 8080. Which line of the usage text changes, and which line of the command?
- Install the folder into another project with a file: dependency and run the command with npx --no-install. Which folder holds the link, and why does --no-install work there?
- Make the command accept a second argument, a folder of documents to index. Which of the three statuses does a missing folder get, and which one a folder with no files?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does the bin field of a package do?
Answer
It maps a command name to a file, and npm links the name when the package is installed
The name is typed by a reader, and the link in node_modules/.bin runs the file.
-
What does this program print?
const bin = { "search-serve": "./bin/search-serve.js" }; console.log(Object.keys(bin)[0], Object.values(bin)[0].endsWith(".js"));Answer
search-serve true
The key is the command name and the value is the file with its extension.
-
Which command shows what a tarball would hold without writing it?
Answer
npm pack --dry-run
The dry run prints the contents and the sizes and leaves the folder as it was.
-
What does this program print?
const report = { entryCount: 7, size: 2300 }; console.log(report.entryCount + " files, " + report.size + " bytes");Answer
7 files, 2300 bytes
The two fields are numbers and the plus turns them into text with the rest of the line.
-
Why is server.js not in the tarball?
Answer
The files list names bin and src, and the probe is a development program
The whitelist decides, and the probe is not something a reader who installs the package needs.
-
What does this program print?
const port = Number("8080"); console.log(Number.isInteger(port), port > 0);Answer
true true
The string is a whole number and it is greater than zero.
-
Which status does a port of 99999 return in this project?
Answer
2
A port that cannot exist is a wrong call, and the convention gives a wrong call the status 2.
-
What does this program print?
const argv = ["8080"]; const port = argv.length === 0 ? 8080 : Number(argv[0]); console.log(port);Answer
8080
The argument is there, so the number of the string is used.
-
What does
npx --yes .do in the folder of the package?Answer
It takes the folder as the package and runs the command its bin names
A dot is the package of the current folder, and --yes answers the fetch question.
-
Why does the command close the server when it gets SIGINT?
Answer
So the server stops accepting and the process can end after the last answer
A listening socket keeps the process alive, and a graceful close lets a request in flight finish.
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. The command that serves was stopped by timeout after one second, which is why its status is 124.
Article author: Arthur Isaev