codejump
EasyJavaScriptTypeScript

Node.js — Parse CLI Arguments

Node.jsBackendCLI

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 --gzip

Inside 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.

OptionValueDefault
first positionalfolder to serve (root)'.'
--port, -pport number3000
--hostinterface to listen on'127.0.0.1'
--gzipboolean flagfalse

Return { root, port, host, gzip } with port as a number.

Errors

Return { error } instead of options when:

  • parseArgs throws (unknown option, option without its value): error is 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

Test #1No arguments: every default
Input: [["node","serve.js"]]
Output: {"gzip":false,"host":"127.0.0.1","port":3000,"root":"."}
Test #2Folder, long port option and flag
Input: [["node","serve.js","./public","--port","8080","--gzip"]]
Output: {"gzip":true,"host":"127.0.0.1","port":8080,"root":"./public"}
Test #3Short option before the folder
Input: [["node","serve.js","-p","9000","site"]]
Output: {"gzip":false,"host":"127.0.0.1","port":9000,"root":"site"}
Test #4Port out of range
Input: [["node","serve.js","--port=0"]]
Output: {"error":"Invalid port: 0"}
Test #5Unknown option
Input: [["node","serve.js","--verbose"]]
Output: {"error":"ERR_PARSE_ARGS_UNKNOWN_OPTION"}