Node.js — Parse CLI Arguments
Welcome to tinyserve, the project of this path: a static file server written with nothing but
Node's core modules — no npm install. Every exercise builds one piece of it. First piece: its
command line.
node serve.js ./public --port 8080 --gzipInside a Node program, process.argv holds that command as an array. Its first two entries are
the path of the node binary and of the script; what the user typed starts at index 2.
Your task
Write parseServeArgs(argv). argv is shaped like process.argv. Use
[`util.parseArgs`](https://nodejs.org/api/util.html#utilparseargsconfig), built into Node since
v18.3, rather than looping over the strings yourself.
| Option | Value | Default |
|---|---|---|
| first positional | folder to serve (root) | '.' |
--port, -p | port number | 3000 |
--host | interface to listen on | '127.0.0.1' |
--gzip | boolean flag | false |
Return { root, port, host, gzip } with port as a number.
Errors
Return { error } instead of options when:
parseArgsthrows (unknown option, option without its value):erroris the thrown error's
code, e.g. 'ERR_PARSE_ARGS_UNKNOWN_OPTION'. Node errors carry a stable code;
their messages change between versions, so code that reacts to errors checks the code.
- more than one positional is given:
'Too many arguments'. - the port is not made of digits only, or is outside 1–65535:
'Invalid port: <value>'.
Example
parseServeArgs(['node', 'serve.js', './public', '-p', '8080', '--gzip']);
// → { root: './public', port: 8080, host: '127.0.0.1', gzip: true }
parseServeArgs(['node', 'serve.js', '--verbose']);
// → { error: 'ERR_PARSE_ARGS_UNKNOWN_OPTION' }The solve function at the bottom is the test driver: it calls your function with each test's
input. You only edit parseServeArgs.
Sample tests