Essential Node.js runtime and npm package manager commands, APIs, and patterns. Covers npm workflows, the Node.js CLI, file system, HTTP, streams, events, and common async patterns. Bookmark this page for quick reference.
| Command | Description |
npm init | Create a new package.json interactively |
npm init -y | Create package.json with default values (skip prompts) |
npm install <pkg> | Install a package and add it to dependencies |
npm install -D <pkg> | Install a package as a dev dependency |
npm install -g <pkg> | Install a package globally |
npm install | Install all dependencies from package.json |
npm uninstall <pkg> | Remove a package from node_modules and package.json |
npm update | Update all packages to latest allowed by semver ranges |
npm update <pkg> | Update a specific package |
npm list | List installed packages (tree view) |
npm list --depth=0 | List only top-level installed packages |
npm outdated | Show packages with newer versions available |
npm audit | Scan dependencies for known security vulnerabilities |
npm audit fix | Automatically fix vulnerable dependencies |
npm run <script> | Run a script defined in package.json |
npm test | Shortcut for npm run test |
npm start | Shortcut for npm run start |
npm cache clean --force | Clear the local npm cache |
npm pack | Create a tarball from a package |
npm publish | Publish a package to the npm registry |
| Field / Syntax | Description |
"scripts": { "start": "node app.js" } | Define runnable scripts via npm run <name> |
"scripts": { "dev": "nodemon app.js" } | Custom script for development with auto-restart |
"scripts": { "prestart": "npm run build" } | Pre-hook runs automatically before start |
"dependencies": { "express": "^4.18.0" } | Production dependencies installed by default |
"devDependencies": { "jest": "^29.0.0" } | Dev-only dependencies (testing, linting, build tools) |
"engines": { "node": ">=18.0.0" } | Specify required Node.js version |
"main": "index.js" | Entry point when package is required |
"type": "module" | Enable ES module syntax (import/export) by default |
"^1.2.3" | Caret: allows minor + patch updates (1.x.x) |
"~1.2.3" | Tilde: allows only patch updates (1.2.x) |
"1.2.3" | Exact: pins to this specific version |
"*" | Any version (not recommended for production) |
">=1.0.0 <2.0.0" | Range: any version from 1.0.0 up to (not including) 2.0.0 |
| Command | Description |
npx <pkg> | Run a package without installing it globally |
npx create-react-app my-app | Scaffold a new React project |
npx create-next-app@latest | Scaffold a new Next.js project with latest version |
npx ts-node script.ts | Run a TypeScript file directly |
npx eslint . | Run ESLint without global install |
npx prettier --write "**/*.js" | Format all JS files with Prettier |
npx serve | Start a static file server in the current directory |
npx npm-check-updates -u | Update all version ranges in package.json to latest |
| Command | Description |
node app.js | Run a JavaScript file with Node.js |
node -e "console.log(1+1)" | Evaluate a JavaScript expression inline |
node --watch app.js | Run with file watcher (auto-restart on changes, Node 18+) |
node --inspect app.js | Start with Chrome DevTools debugger on port 9229 |
node --inspect-brk app.js | Start debugger and break on first line |
node --env-file=.env app.js | Load environment variables from a file (Node 20+) |
node -p "process.version" | Evaluate and print result |
node | Start the interactive REPL (Read-Eval-Print Loop) |
.help | REPL: show available commands |
.exit | REPL: exit the REPL session |
.load file.js | REPL: load and execute a file |
node --max-old-space-size=4096 app.js | Increase V8 heap memory limit to 4GB |
node --test | Run built-in test runner (Node 20+) |
| Code | Description |
const fs = require('fs'); | Import the file system module |
const fsp = require('fs/promises'); | Import promise-based fs API |
fs.readFileSync('f.txt', 'utf8') | Read a file synchronously as a string |
await fsp.readFile('f.txt', 'utf8') | Read a file asynchronously (promise) |
fs.writeFileSync('f.txt', data) | Write data to a file synchronously |
await fsp.writeFile('f.txt', data) | Write data to a file asynchronously (promise) |
await fsp.appendFile('f.txt', data) | Append data to a file |
await fsp.mkdir('dir', {recursive:true}) | Create a directory (and parents if needed) |
await fsp.readdir('dir') | List files in a directory |
await fsp.rm('f.txt') | Delete a file |
await fsp.rm('dir', {recursive:true}) | Delete a directory and its contents |
await fsp.stat('f.txt') | Get file metadata (size, dates, isFile, isDirectory) |
await fsp.rename('old', 'new') | Rename or move a file |
await fsp.copyFile('src', 'dest') | Copy a file |
fs.existsSync('f.txt') | Check if a file or directory exists |
fs.watch('dir', callback) | Watch a file or directory for changes |
const path = require('path'); | Import the path module |
path.join('dir', 'file.txt') | Join path segments with OS-specific separator |
path.resolve('file.txt') | Resolve to an absolute path |
path.basename('/a/b/file.txt') | Get filename: 'file.txt' |
path.dirname('/a/b/file.txt') | Get directory: '/a/b' |
path.extname('file.txt') | Get extension: '.txt' |
path.parse('/a/b/file.txt') | Parse path into {root, dir, base, name, ext} |
__dirname | Directory of the current module (CommonJS only) |
__filename | Full path of the current module (CommonJS only) |
| Code | Description |
const http = require('http'); | Import the HTTP module |
http.createServer((req, res) => {...}) | Create an HTTP server with a request handler |
server.listen(3000) | Start listening on port 3000 |
req.method | HTTP method: 'GET', 'POST', etc. |
req.url | Request URL path (e.g., '/api/users') |
req.headers | Object containing request headers |
res.writeHead(200, {'Content-Type': 'application/json'}) | Set response status code and headers |
res.end(JSON.stringify(data)) | Send response body and finish |
res.statusCode = 404 | Set the response status code |
res.setHeader('Content-Type', 'text/html') | Set a single response header |
http.get(url, (res) => {...}) | Make a GET request |
fetch(url, {method:'POST', body:data}) | Built-in fetch API (Node 18+ stable) |
| Code | Description |
const {EventEmitter} = require('events'); | Import EventEmitter class |
const emitter = new EventEmitter(); | Create a new event emitter instance |
emitter.on('event', callback) | Register a listener for an event |
emitter.once('event', callback) | Register a one-time listener (auto-removed after first call) |
emitter.emit('event', arg1, arg2) | Emit an event with arguments to all listeners |
emitter.off('event', callback) | Remove a specific listener |
emitter.removeAllListeners('event') | Remove all listeners for an event |
emitter.listenerCount('event') | Return the number of listeners for an event |
emitter.setMaxListeners(20) | Increase max listeners (default 10) to avoid warnings |
emitter.eventNames() | Return array of event names with registered listeners |
| Code | Description |
const readable = fs.createReadStream('f.txt'); | Create a readable stream from a file |
const writable = fs.createWriteStream('out.txt'); | Create a writable stream to a file |
readable.pipe(writable) | Pipe data from readable to writable stream |
readable.on('data', (chunk) => {...}) | Handle each chunk of data as it arrives |
readable.on('end', () => {...}) | Handle stream completion |
readable.on('error', (err) => {...}) | Handle stream errors |
writable.write(data) | Write a chunk of data to the stream |
writable.end() | Signal that no more data will be written |
const {pipeline} = require('stream/promises'); | Import promise-based pipeline utility |
await pipeline(readable, transform, writable) | Chain streams with automatic error handling |
const {Transform} = require('stream'); | Import Transform stream class |
new Transform({transform(chunk,enc,cb){...}}) | Create a transform stream to modify data in transit |
const {Readable} = require('stream'); | Import Readable class for custom streams |
Readable.from(['a','b','c']) | Create a readable stream from an iterable |
| Code | Description |
process.env.NODE_ENV | Access environment variables |
process.env.PORT || 3000 | Use env variable with fallback default |
process.argv | Array of command-line arguments [node, script, ...args] |
process.argv.slice(2) | Get user-provided arguments only |
process.cwd() | Get the current working directory |
process.exit(0) | Exit with success code (0 = success, 1 = error) |
process.exit(1) | Exit with error code |
process.pid | Get the current process ID |
process.platform | OS platform: 'linux', 'darwin', 'win32' |
process.memoryUsage() | Get memory usage stats (rss, heapTotal, heapUsed) |
process.uptime() | Get process uptime in seconds |
process.stdin | Readable stream for standard input |
process.stdout.write('text') | Write to stdout without newline (unlike console.log) |
process.stderr.write('error') | Write to stderr stream |
process.on('uncaughtException', cb) | Handle uncaught exceptions (last resort) |
process.on('SIGTERM', () => {...}) | Handle termination signal for graceful shutdown |
process.nextTick(callback) | Schedule callback before next I/O cycle |
| Code | Description |
const mod = require('./module'); | CommonJS: import a local module |
const express = require('express'); | CommonJS: import an npm package |
module.exports = myFunction; | CommonJS: export a single value |
module.exports = { fn1, fn2 }; | CommonJS: export multiple named values |
exports.myFunc = function() {...}; | CommonJS: shorthand for named exports |
const {readFile} = require('fs'); | CommonJS: destructured import |
import express from 'express'; | ES Module: default import (requires "type":"module") |
import {readFile} from 'fs/promises'; | ES Module: named import |
import * as fs from 'fs'; | ES Module: namespace import |
export default function() {...} | ES Module: default export |
export { fn1, fn2 }; | ES Module: named exports |
export const name = 'value'; | ES Module: inline named export |
import('./module.js').then(m => ...) | Dynamic import (works in both CommonJS and ESM) |
require.resolve('express') | Get the resolved file path of a module |
| Code | Description |
fs.readFile('f', (err, data) => {...}) | Error-first callback pattern (Node.js convention) |
if (err) return callback(err); | Early return on error in callbacks |
new Promise((resolve, reject) => {...}) | Create a new Promise |
promise.then(data => ...).catch(err => ...) | Handle promise resolution and rejection |
Promise.all([p1, p2, p3]) | Wait for all promises to resolve (fails fast) |
Promise.allSettled([p1, p2]) | Wait for all promises regardless of outcome |
Promise.race([p1, p2]) | Resolve/reject with the first settled promise |
async function run() {...} | Declare an async function (always returns a Promise) |
const data = await readFile('f'); | Await a promise inside an async function |
try { await op(); } catch(e) {...} | Error handling with async/await |
const {promisify} = require('util'); | Import promisify utility |
const readFile = promisify(fs.readFile); | Convert callback-based function to promise-based |
setTimeout(fn, 1000) | Execute function after 1 second delay |
setInterval(fn, 5000) | Execute function every 5 seconds |
setImmediate(fn) | Execute function on next iteration of event loop |
const {setTimeout} = require('timers/promises'); | Import promise-based timer (Node 16+) |
await setTimeout(1000) | Async sleep for 1 second |
| Code | Description |
const os = require('os'); | Import OS info module |
os.cpus().length | Get the number of CPU cores |
os.totalmem() / 1024**3 | Get total system memory in GB |
os.freemem() | Get free system memory in bytes |
os.homedir() | Get the user's home directory path |
os.tmpdir() | Get the OS temporary directory path |
os.hostname() | Get the system hostname |
const crypto = require('crypto'); | Import cryptography module |
crypto.randomBytes(16).toString('hex') | Generate a random hex string (32 chars) |
crypto.randomUUID() | Generate a random UUID v4 |
crypto.createHash('sha256').update(data).digest('hex') | Compute SHA-256 hash of data |
const {URL} = require('url'); | Import URL parser class |
new URL('https://example.com/path?q=1') | Parse a URL into components (href, hostname, pathname, searchParams) |
url.searchParams.get('q') | Get a query parameter value |
new URLSearchParams({a:'1',b:'2'}).toString() | Build a query string: 'a=1&b=2' |
const {exec} = require('child_process'); | Import child process module |
exec('ls -la', (err, stdout) => {...}) | Run a shell command and capture output |
const {execSync} = require('child_process'); | Import synchronous exec |
execSync('git status', {encoding:'utf8'}) | Run a shell command synchronously |
const {spawn} = require('child_process'); | Import spawn for long-running processes |
spawn('node', ['app.js'], {stdio:'inherit'}) | Spawn a child process with inherited I/O |
const {inspect} = require('util'); | Import util.inspect for pretty-printing |
inspect(obj, {depth:null, colors:true}) | Deep-inspect an object with color output |
const {Worker} = require('worker_threads'); | Import worker threads for parallel execution |
new Worker('./worker.js', {workerData:{}}) | Spawn a worker thread with initial data |