Skip to content

Instantly share code, notes, and snippets.

@schalkneethling
Last active December 29, 2021 11:50
Show Gist options
  • Save schalkneethling/d3754a9efc5ef61d0ce43f1905cd9007 to your computer and use it in GitHub Desktop.
Save schalkneethling/d3754a9efc5ef61d0ce43f1905cd9007 to your computer and use it in GitHub Desktop.
A bunch of useful and perhaps not commonly known Nodejs tips and notes
'use strict'
const { pipeline } = require('stream')
const { join } = require('path')
const { createReadStream, createWriteStream } = require('fs')
// this is highly performant for large files
// as the read and write happens in small chunks
pipeline(
createReadStream(__filename),
createWriteStream(join(__dirname, 'out.txt')),
(err) => {
if (err) {
console.error(err)
return
}
console.log('finished writing')
}
)
// run with node delete-dir-recursive.js
import fs from "fs";
// @TODO: folder should be based on arg provided by user
fs.rmdirSync('node_modules', { recursive: true });
// Alternatively, you can run the following directly in the terminal
// In this instance `fs` is available in context
// node -e "fs.rmdirSync('node_modules', { recursive: true })"

When using CommonJS modules in Nodejs the following two variables are alwasy available as globals:

  • __filename - absolute path to the currently executing file
  • __dirname - the absolute path to the directory that the currently executing file is in

More and more of Nodejs modules are moving to EcmaScript modules and in these cases, the above two no longer exists. Here is how to get the equivalent:

import {fileURLToPath} from 'node:url';
import path from 'node:path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(fileURLToPath(import.meta.url));

However, please do read the additional information here where the above originated from.

process.memoryUsage() returns an object with rss, heapTotal, heapUsed and external

  • rss - Resident set size is total used memory in RAM alone for the process
  • heapUsed - Total amount of memory used across both RAM and swap space for the process
  • heapTotal - Total memory allocated for a process
  • external - Memory usage by the C layer

Nodejs command line options

See all Nodejs command line flags

node --help

See all V8 command line flags

node --v8-options

check

Parse the JS without actually executing the app

node --check | -c app.js

print

Print the output of the expression to stdout

# prints 2
node --print | -p "1+1"

eval

Evaluate the expression

node --eval | -e "1+1"
# prints 2 and then undefined as console.log returns undefined
node -e "console.log(1+1)"

require

Preload a module before executing

// preload.js
console.log("I was preloaded");
// app.js
console.log("Main entry file");
node -r ./preload.js app.js
# ❯ node -r ./preload.js app.js
# I was preloaded
# Main entry point

Increase stack trace limit

node --stack-trace-limit=101 app.js 

Setting the limit to a number greater than the potential output will ensure all lines are shown.

node --stack-trace-limit=1001 app.js 

inspect mode

You can debug a process using the Chrome Devtools remote debugging protocol, for example:

node --inspect app.js

Unless you have alrady set a breakpoint, the above will allow remote debugging but will run the entirety of the program without yielding. You can automatically add a breakpoint at the start of the program by using the following variation:

node --inspect-brk app.js

Install only production dependencies

npm install --production

aliases

Alias for npm run start

npm start

Alias for npm run test

npm test
// Running this on the command line will output all `js` files in the current directory.
// No need to `require` as the core modules are directly accessible via their namespace in this context.
node -p "fs.readdirSync('.').filter((f) => /.js$/.test(f))"
// run with node simple-ls-node.js
import fs from "fs";
// @TODO: folder should be based on arg provided by user
console.log(fs.readdirSync(".").join("\n"));
// Alternatively, you can run the following directly in the terminal
// In this instance `fs` is available in context
// node -p "fs.readdirSync('.').join('\n')"
'use strict'
const { watch } = require('fs')
watch('.', (evt, filename) => {
console.log(evt, filename)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment