Skip to main content

Programming languages · Intermediate · 16 min

Build a Node.js command-line tool with util.parseArgs and no dependencies

By Padding · Updated 18 Nov 2026
node:26 (Debian) · Node.js 26.13.1 LTS

You will build a zero-dependency csvtojson command in Node.js 26 that parses flags with util.parseArgs, reads a file or standard input, reports errors with exit codes, colours its output only for a terminal, loads a .env file and runs from any folder after npm link.

On this page

Most small jobs on a computer start as a command: convert this file, check that folder, send that report. Node.js can do these jobs well, and since Node.js 18.3 (a stable API since Node.js 20) it can also read command-line flags on its own. util.parseArgs turns -p --delimiter ';' data.csv into a plain object, with short flags, defaults and type checks, so you no longer need a package such as yargs or commander for a modest tool.

In this tutorial you build csvtojson, a command that turns CSV into JSON. It takes a file name or reads from a pipe, has short and long flags, prints errors on the error stream with a proper exit code, shows a coloured summary that switches itself off when it is not going to a terminal, reads a default from a .env file, and installs as a real command with npm link. Everything comes from the Node.js standard library, so there is nothing to download from npm, which also helps on prepaid or metered data.

This is a different tool from the to-do list app, which asks questions interactively. A command like csvtojson takes all its input up front, which is what lets you use it in scripts and pipelines.

Step 1 · Create the project and a CSV parser

Make a throwaway project folder and a package.json. "type": "module" lets you use import, and the bin field names the command npm will install in the last steps:

Bash
mkdir -p ~/csvtojson-demo/bin ~/csvtojson-demo/lib
cd ~/csvtojson-demo
cat > package.json <<'JSON'
{
  "name": "csvtojson-demo",
  "version": "1.0.0",
  "description": "Convert CSV to JSON from the command line",
  "type": "module",
  "bin": {
    "csvtojson": "bin/csvtojson.js"
  },
  "engines": {
    "node": ">=26"
  },
  "license": "MIT"
}
JSON

The CSV work goes in its own module, so the command file stays about arguments and input. The parser walks the text one character at a time. A field wrapped in double quotes may contain the delimiter, a line break or a doubled quote ("" means one "), which is where naive split(',') code breaks:

Bash
cat > lib/csv.js <<'JS'
// Split CSV text into rows of fields. Handles quoted fields that contain the
// delimiter, line breaks or doubled quotes (""), and both \n and \r\n endings.
export function parseCsv(input, delimiter = ',') {
  const text = input.replace(/^\uFEFF/, '');
  const rows = [];
  let row = [];
  let field = '';
  let quoted = false;

  for (let i = 0; i < text.length; i++) {
    const ch = text[i];
    if (quoted) {
      if (ch === '"' && text[i + 1] === '"') {
        field += '"';
        i++;
      } else if (ch === '"') {
        quoted = false;
      } else {
        field += ch;
      }
    } else if (ch === '"') {
      quoted = true;
    } else if (ch === delimiter) {
      row.push(field);
      field = '';
    } else if (ch === '\n' || ch === '\r') {
      if (ch === '\r' && text[i + 1] === '\n') i++;
      row.push(field);
      rows.push(row);
      row = [];
      field = '';
    } else {
      field += ch;
    }
  }
  if (field !== '' || row.length > 0) {
    row.push(field);
    rows.push(row);
  }
  return rows.filter((r) => !(r.length === 1 && r[0] === ''));
}

// Use the first row as keys and turn every other row into an object.
export function toRecords(rows) {
  const [header = [], ...data] = rows;
  return data.map((cells) =>
    Object.fromEntries(header.map((name, i) => [name, cells[i] ?? ''])),
  );
}
JS

The first line strips a byte order mark, which spreadsheet programs often put at the start of a CSV export. Add a sample file. The names use accented letters and a Yorùbá tone mark on purpose: real data is multilingual, and you want to see that it comes through untouched:

Bash
cat > people.csv <<'CSV'
name,city,role
Adébáyọ̀ Okafor,Lagos,engineer
Wanjiru Kamau,Nairobi,"designer, lead"
Thandiwe Dlamini,Durban,"product ""ops"""
CSV

Check it worked

Call the parser directly:

Bash
node --input-type=module -e "
import { readFileSync } from 'node:fs';
import { parseCsv, toRecords } from './lib/csv.js';
console.log(toRecords(parseCsv(readFileSync('people.csv', 'utf8'))));
"

You see three objects. Wanjiru's role is 'designer, lead' with the comma kept, Thandiwe's is 'product "ops"', and Adébáyọ̀ is spelled exactly as in the file.

Step 2 · Describe the options with util.parseArgs

parseArgs needs a description of every option: its long name, whether it is a string or a boolean, an optional one-letter short alias and an optional default. Put that description and the help text side by side in one module, so they are easy to keep in step:

Bash
cat > lib/options.js <<'JS'
export const options = {
  delimiter: { type: 'string', short: 'd', default: process.env.CSVTOJSON_DELIMITER ?? ',' },
  pretty: { type: 'boolean', short: 'p', default: false },
  header: { type: 'boolean', default: true },
  quiet: { type: 'boolean', short: 'q', default: false },
  help: { type: 'boolean', short: 'h', default: false },
  version: { type: 'boolean', short: 'v', default: false },
};

export const usage = `Usage: csvtojson [options] [file]

Convert CSV to JSON. Reads standard input when no file is given.

Options:
  -d, --delimiter <char>  Field separator (default: "," or $CSVTOJSON_DELIMITER)
  -p, --pretty            Indent the JSON
      --no-header         Treat the first row as data and print arrays
  -q, --quiet             Do not print the summary line
  -h, --help              Show this help
  -v, --version           Show the version
`;
JS

The delimiter default reads an environment variable first; you use that in a later step. header defaults to true, and you switch it off with --no-header, which parseArgs accepts once you pass allowNegative: true.

Before building the whole command, write a short script that only prints what parseArgs returns:

Bash
cat > try-args.js <<'JS'
import { parseArgs } from 'node:util';
import { options } from './lib/options.js';

const { values, positionals } = parseArgs({
  options,
  allowPositionals: true,
  allowNegative: true,
});
console.log(JSON.stringify({ values, positionals }));
JS
node try-args.js people.csv
node try-args.js -pq -d ';' --no-header people.csv
node try-args.js --delimiter=';' -- -odd-name.csv

parseArgs reads process.argv without the first two entries (the node binary and the script path). allowPositionals: true lets it accept plain words such as the file name; without it, any word that is not an option is an error.

Check it worked

The three lines show the parser at work:

  • With only people.csv, every value is its default and positionals is ["people.csv"].
  • -pq is two short flags grouped together, so pretty and quiet are true, -d ';' sets delimiter, and --no-header makes header false.
  • --delimiter=';' is the = form of the same option. Everything after -- counts as a positional, even -odd-name.csv, which would otherwise look like a flag.

Now pass an option it does not know:

Bash
node try-args.js --colour || echo "failed with exit code $?"

Node.js prints a stack trace for ERR_PARSE_ARGS_UNKNOWN_OPTION and the script ends with exit code 1. That is strict mode, the default, doing its job, but a stack trace is no way to greet someone who mistyped a flag. The next steps catch it.

Step 3 · Write the command

Create the command file. The first line, the shebang, tells the operating system to run the file with whichever node comes first on your PATH:

Bash
cat > bin/csvtojson.js <<'JS'
#!/usr/bin/env node
import { readFile } from 'node:fs/promises';
import { text } from 'node:stream/consumers';
import { parseArgs, styleText } from 'node:util';
import { parseCsv, toRecords } from '../lib/csv.js';
import { options, usage } from '../lib/options.js';

// Print an error in red (only if stderr can show colour) and set the exit code.
function fail(message, code = 1) {
  console.error(styleText('red', `csvtojson: ${message}`, { stream: process.stderr }));
  process.exitCode = code;
}

async function main() {
  let parsed;
  try {
    parsed = parseArgs({ options, allowPositionals: true, allowNegative: true });
  } catch (err) {
    fail(`${err.message}\nRun 'csvtojson --help' for usage.`, 2);
    return;
  }
  const { values, positionals } = parsed;

  if (values.help) {
    process.stdout.write(usage);
    return;
  }
  if (values.version) {
    const pkg = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
    console.log(pkg.version);
    return;
  }
  if (positionals.length > 1) {
    fail('give at most one file', 2);
    return;
  }
  if (values.delimiter.length !== 1) {
    fail(`the delimiter must be one character, got '${values.delimiter}'`, 2);
    return;
  }

  const [file] = positionals;
  let input;
  if (file && file !== '-') {
    try {
      input = await readFile(file, 'utf8');
    } catch (err) {
      fail(`cannot read ${file} (${err.code})`);
      return;
    }
  } else if (process.stdin.isTTY) {
    fail("no input: give a file, or pipe CSV in with 'cat data.csv | csvtojson'", 2);
    return;
  } else {
    input = await text(process.stdin);
  }

  const rows = parseCsv(input, values.delimiter);
  const result = values.header ? toRecords(rows) : rows;
  process.stdout.write(JSON.stringify(result, null, values.pretty ? 2 : undefined) + '\n');

  if (!values.quiet) {
    const summary = `Converted ${result.length} ${result.length === 1 ? 'row' : 'rows'}`;
    console.error(styleText('green', summary, { stream: process.stderr }));
  }
}

await main();
JS
chmod +x bin/csvtojson.js

How the input is chosen:

  • A file name reads that file. A lone - means standard input, a common convention for commands that take files.
  • With no file, the command reads everything piped into it. text() from node:stream/consumers collects a stream into one string.
  • With no file and nothing piped in, standard input is your keyboard (process.stdin.isTTY is true). Waiting there would look like a hang, so the command says what it needs instead.

The --version flag reads package.json relative to the script file through import.meta.url, not the folder you run it from, so it keeps working after you install the command. The JSON goes to standard output and the summary goes to standard error. That split is what lets you pipe the JSON into another program while you still see the summary.

Run it on the file, then with flags, then with a pipe:

Bash
./bin/csvtojson.js people.csv
./bin/csvtojson.js -p --no-header people.csv
cat people.csv | ./bin/csvtojson.js -q > from-pipe.json
node -e "console.log(JSON.parse(require('node:fs').readFileSync('from-pipe.json', 'utf8'))[1].role)"

When you run the command with nothing piped in, it stops with the no-input message and does not wait for typing:

Bash
./bin/csvtojson.js

Check it worked

The first command prints one line of JSON with three objects, then Converted 3 rows. The -p --no-header run prints indented arrays, and the first array is the header row "name", "city", "role". The pipe run prints nothing on screen, because -q hides the summary and the JSON went to from-pipe.json. The last command reads that file back and prints designer, lead. Try ./bin/csvtojson.js --help and ./bin/csvtojson.js -v too: the help text and 1.0.0.

Step 4 · Report errors on stderr with exit codes

Every error goes through fail(). It does three things:

  • It writes to standard error with console.error, so an error message never ends up inside a JSON file someone redirected output into.
  • It starts the message with the command name, csvtojson:, so in a long script log you can tell which command complained.
  • It sets process.exitCode and lets main() return, rather than calling process.exit().

The last point matters for commands that write a lot. When standard output is a pipe, Node.js may still have data waiting to be written. process.exit() ends the process at once, even with that work pending, so the end of your output can go missing. Setting process.exitCode lets Node.js finish writing and then exit with your code.

The exit code is how scripts know what happened. This tool uses 0 for success, 1 when it could not do the work (a missing file), and 2 when it was called wrongly (a bad option), a common convention. Try three mistakes. || echo prints the code when the command fails:

Bash
./bin/csvtojson.js missing.csv || echo "exit code $?"
./bin/csvtojson.js --colour || echo "exit code $?"
./bin/csvtojson.js -d ';;' people.csv || echo "exit code $?"

Check it worked

You see csvtojson: cannot read missing.csv (ENOENT) and exit code 1. The unknown option now gives a two-line message that starts csvtojson: Unknown option '--colour' and ends with the hint to run --help, with no stack trace, and exit code 2. The double delimiter gives the delimiter must be one character, got ';;' and exit code 2.

Step 5 · Add colour that turns off when piped

The summary is green and errors are red, but only when a person is looking at them. styleText checks the stream you pass in { stream: process.stderr }. If that stream is a terminal, it adds the colour codes. If the stream is a file or a pipe, it returns the plain text. It also respects the NO_COLOR and NODE_DISABLE_COLORS environment variables, which some people set to switch colour off everywhere, and FORCE_COLOR, which switches it on.

The check is per stream. Piping the JSON with | other-command changes standard output only, so the summary on standard error is still green on your screen. To see what reaches a file, redirect standard error and show hidden characters with cat -v:

Bash
./bin/csvtojson.js people.csv > people.json 2> summary.txt
cat -v summary.txt
FORCE_COLOR=1 ./bin/csvtojson.js people.csv > people.json 2> summary.txt
cat -v summary.txt

If you write colour codes yourself, such as '\x1b[32m', you lose all of this and log files fill up with ^[[32m noise. Let styleText decide.

Check it worked

The first cat -v prints Converted 3 rows and nothing else. The second, with FORCE_COLOR=1, prints ^[[32mConverted 3 rows^[[39m: the escape codes for green and back to normal, which styleText added because you forced it. Run ./bin/csvtojson.js people.csv without redirects in a colour terminal and the summary shows in green.

Step 6 · Read a default from a .env file

Some teams export CSV with semicolons, because in many locales the comma is the decimal separator. Typing -d ';' every time gets old. The options module already takes the default from CSVTOJSON_DELIMITER when it is set, and Node.js can load that variable from a file with --env-file, with no dotenv package.

Create a semicolon file and a .env file. Quoting the value is a good habit: it keeps values that contain spaces or # intact.

Bash
printf 'name;city\nKofi Mensah;Accra\n' > semicolons.csv
cat > .env <<'ENV'
CSVTOJSON_DELIMITER=";"
ENV
node --env-file=.env bin/csvtojson.js semicolons.csv
CSVTOJSON_DELIMITER='|' node --env-file=.env bin/csvtojson.js semicolons.csv
node --env-file=.env bin/csvtojson.js -d ',' semicolons.csv

--env-file is an option for node itself, so it goes before the script name. The order of precedence is: a flag on the command line wins, then a variable already set in your shell, then the value in .env, then the built-in ,. Node.js does not overwrite a variable that is already set in the environment. If the file might not exist, use --env-file-if-exists=.env instead, which skips a missing file without an error.

The .env file here holds a harmless setting. When a tool needs a secret, such as an API token, the same mechanism works, but keep the file out of version control (add .env to .gitignore) and never pass the secret as a command-line flag, where it lands in shell history.

Check it worked

The first run prints [{"name":"Kofi Mensah","city":"Accra"}]: the .env file set the delimiter. The second prints one key, "name;city", because the shell's | beat the file. The third also prints "name;city", because -d ',' beat both.

Step 7 · Install the command with npm link

So far you have run the tool as ./bin/csvtojson.js from its folder. npm link makes it a command on your PATH. It creates a link to your project in npm's global folder and adds a csvtojson command that points at the file named in bin. On macOS and Linux the shebang line runs it with Node.js. On Windows, npm writes small wrapper scripts so the same bin entry works there.

First check that the name is free:

Bash
command -v csvtojson || echo "csvtojson is free to use"

If this prints a path, you already have a command with that name. Change the key under bin in package.json to something else, such as csvtojson-demo, and use that name below. Then link the project:

Bash
npm link

If npm stops with an EACCES permission error, your global packages still install to a system folder. Set up a folder in your home directory as in the Node.js install tutorial rather than running npm link with sudo.

Now go somewhere else and use the command like any other:

Bash
cd ~
command -v csvtojson
csvtojson --version
csvtojson -q ~/csvtojson-demo/people.csv
printf 'item,price\nmaize,1200\n' | csvtojson -p

The link points at your project folder, so any edit you make to bin/csvtojson.js or lib/ takes effect the next time you run csvtojson, with no reinstall. Note that every value comes out as a string, such as "1200"; CSV has no types, so turning numbers into numbers is a choice your tool would have to make on purpose.

Check it worked

command -v csvtojson prints a path inside npm's global bin folder. csvtojson --version prints 1.0.0 from your home folder, the people file converts, and the piped CSV prints indented JSON with "item": "maize" and "price": "1200", then Converted 1 row.

Step 8 · Clean up

Remove the global command first, then the project. Removing the folder alone would leave a broken csvtojson link behind:

Bash
npm rm --global csvtojson-demo
rm -rf ~/csvtojson-demo

Your shell remembers where it last found each command, so clear that memory with hash -r before checking that the command is gone:

Bash
hash -r
command -v csvtojson || echo "csvtojson is gone"

Check it worked

After hash -r, command -v csvtojson prints nothing and the line prints csvtojson is gone, and ls ~/csvtojson-demo reports that there is no such file or directory. Node.js and npm stay installed.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.