Sunday, June 7, 2026

Nodejs : Useful miniscripts


Since Node.js is a scripting language, we can use the "-e" switch to evaluate the text which immediately follows. This allows us to run small scripts ( may be one-liners) without saving them to a .js file. These Node.js one-liners are extremely useful for quick automation, debugging, testing, and system administration tasks directly from the terminal without creating separate JavaScript files. The best one I think is the first one, which allows us to directly test a web server, which on accessing port 3000 will print "Hello" in the browser. 

Use Case Terminal Command What It Does
Instant HTTP Server
node -e "require('http').createServer((req,res)=>res.end('Hello')).listen(3000)"
Spins up a minimal web server on port 3000 that responds to every request with "Hello".
JSON Pretty-Printer
node -e "console.log(JSON.stringify(JSON.parse(process.argv[1]), null, 2))" '{"a":1,"b":2}'
Takes a raw, minified JSON string from the arguments and formats it with clean, readable spacing.
File Downloader
node -e "require('https').get('https://example.com', r => r.pipe(process.stdout))"
Acts as a lightweight curl alternative to stream data from a URL straight to your terminal.
System Resource Check
node -e "const os = require('os'); console.log({ free_GB: (os.freemem()/1024**3).toFixed(2), total_GB: (os.totalmem()/1024**3).toFixed(2), cpus: os.cpus().length })"
Queries the host machine's total/free RAM (converted to GB) and displays the CPU core count.
Secure Token Generator
node -e "console.log(require('crypto').randomBytes(20).toString('hex'))"
Uses Node's crypto module to generate a random, secure 40-character hex string for passwords or keys.
JSON Directory Lister
node -e "console.log(JSON.stringify(require('fs').readdirSync('.')))"
Scans the current folder and outputs the list of files formatted cleanly as a valid JSON array.
Quick Tip:
All of these commands use Node.js's -e flag, which allows JavaScript code to be executed directly from the terminal without creating a separate .js file.

No comments:

Post a Comment

Nodejs : Useful miniscripts

Since Node.js is a scripting language, we can use the "-e" switch to evaluate the text which immediately follows. This allows ...