Frontier Software

Node

After gaining some experience at using Bash’s associative arrays to handle JSON, I decided a better approach would be to rather write Unix filters in JavaScript which read JSON from stdin and write the munged JSON to stdout while logging problems to stderr.

Courtesy of node, that can be done, though it required deciphering its jargon. For instance what I’d call a remote procedure call to, say, date, involves using Node’s child_process module.

As a first exercise, let’s rewrite the bash function below:

#!/usr/bin/bash

echo "$(TZ=Africa/Johannesburg date -d "${@: -1}" +%Y-%m-%dT%H:%M:%S+02:00)"

The functions in the child_process module have both asynchronous and synchronous versions which are suffixed with *Sync. For Bash scripts, execSync is usually what we want.

#!/usr/bin/env node

const { argv } = require('node:process');
const { execSync } = require('node:child_process');
str = execSync(`TZ=Africa/Johannesburg date -d "${argv[argv.length - 1]}" +%Y-%m-%dT%H:%M:%S+02:00`); 
console.log(`${str}`);