Node.js and npm Cheat Sheet

Sidebar

Programming · Node.js and npm Cheat Sheet

Running JavaScript with Node.js and managing packages with npm: command-line options, modules, built-ins, package.json, installing, scripts, security, configuration and debugging. Written for Node 24 and npm 11, the versions installed here; the commands and options were run in a scratch project to check they work, and a card records what was found on this machine.

Your Setup (found on this machine)

node -v / npm -vNode v24.18.0 (the 24 line is Long Term Support, nicknamed Krypton) and npm 11.16.0; npx is the same version
npm doctorReports that newer versions exist (npm 12.2.0 and Node 24.21.0 at the time of writing); everything else checked was fine
npm root -gGlobal packages live in C:\Users\emuba\AppData\Roaming\npm; the only global package is @anthropic-ai/claude-code
npm config get registryhttps://registry.npmjs.org/ (the default)
corepack --version0.35.0 is included with Node: corepack enable sets up pnpm and Yarn when you need them
Not installedpnpm, Yarn, nvm, fnm and Volta (no Node version manager); Bun and Deno are absent too
astro-siteYour site's package.json asks for Node 22.12 or newer (engines), which 24.18 satisfies

Running Node

node file.js a bRun a file; the extra words arrive in process.argv.slice(2)
nodeWith no file: the interactive REPL
node -e "code" node -p "expression"Run code from the command line / run an expression and print the result
node --watch file.jsRestart whenever the file (or what it imports) changes; --watch-path=src chooses folders. Not combinable with -e
node --env-file=.env file.jsLoad variables from a file into process.env; --env-file-if-exists does not fail if the file is missing
node --run <script>Run a script from package.json without starting npm (faster)
node file.tsRuns TypeScript directly on this version, but only syntax that can be erased (no enums or other generated code)
node --check file.jsCheck syntax without running
node --testRun test files with the built-in runner; --test-reporter=spec and --experimental-test-coverage work
node -r ./setup.js node --import ./setup.mjsLoad a module before your program (CommonJS / ES module)
node --max-old-space-size=2048Raise the memory limit (megabytes)
node --trace-warnings --no-warnings --disable-warning=CodeShow where warnings come from / hide all / hide one kind
node --inspect --inspect-brkAllow a debugger to connect / also stop on the first line
node --cpu-prof --heap-profWrite CPU or memory profiles for later analysis
node --permission --allow-fs-read=*Run with the permission model: file, network and process access is denied unless allowed
node --helpAll options

The REPL

.helpList the REPL commands
.editorEnter several lines; finish with Ctrl+D
.load file.js .save file.jsRun a file in the session / save what you typed
.break .clearAbandon a multi-line entry / reset the session
_The result of the last expression
TabComplete names; press twice to list the options
.exit Ctrl+D Ctrl+C twiceLeave the REPL

Modules: ESM and CommonJS

import fs from 'node:fs'ES module syntax; the node: prefix marks a built-in
const fs = require('node:fs')CommonJS syntax
"type": "module"In package.json: treat .js files as ES modules (otherwise as CommonJS)
.mjs .cjsFile extensions that force ES module / CommonJS whatever type says
import.meta.dirname import.meta.filenameThis file's folder and path in an ES module (works on this version)
__dirname __filenameThe CommonJS equivalents; not defined in ES modules
await import('./x.js')Load a module while the program runs; top-level await works in ES modules
module.exports = … export default …Share a value from a file
import data from './x.json' with { type: 'json' }Import a JSON file in an ES module (my knowledge)

Built-in Modules and Globals Worth Knowing

node:fs / node:fs/promisesRead and write files (the promise version works with await)
node:path node:os node:urlPaths, system information, URLs
node:http node:httpsServers and requests
node:cryptoHashes, random bytes, encryption
node:child_processRun other programs
node:readline node:events node:stream node:utilRead input a line at a time / events / streams / helpers
node:test node:assertThe built-in test runner and assertions
node:worker_threads node:zlib node:timers/promisesThreads / compression / await-able timers
node:sqliteA built-in SQLite database (present on this version)
fetch WebSocket structuredCloneGlobal functions available without importing (confirmed on this version)
process console Buffer URL AbortController setTimeoutMore globals
72 built-in modulesThat is how many this version lists in require('module').builtinModules

The process Object

process.argvCommand-line words: [node, script, …your arguments]
process.env.NAMEAn environment variable (a string or undefined)
process.cwd() process.platformCurrent folder / win32 here
process.exit(1) process.exitCode = 1Stop now with a code / set the code and finish normally (0 means success)
process.on('SIGINT', fn)Run code when the user presses Ctrl+C
process.memoryUsage() process.uptime()Memory and running time
process.versionsVersions of Node and its parts (V8, OpenSSL, SQLite…)
process.stdin process.stdoutStandard input and output streams

package.json Essentials

npm init -yCreate a package.json with defaults
name version descriptionThe package's identity (version uses semantic versioning: major.minor.patch)
scriptsNamed commands, run with npm run <name>
dependencies devDependenciesPackages needed to run / only to build and test
peerDependencies optionalDependenciesPackages the user must supply / nice to have
main exports binEntry file / public entry points / commands the package installs
typemodule or commonjs
enginesVersions of Node (and npm) that the project supports, e.g. { "node": ">=22.12.0" }
privatetrue prevents publishing by accident
filesWhat goes into the package when published
workspacesSeveral packages in one repository
overridesForce a version of a dependency anywhere in the tree
npm pkg get name npm pkg set scripts.dev="…"Read and edit package.json from the command line
^1.2.3 ~1.2.3 1.2.3 >=1.2 *Version ranges: any 1.x.y at least 1.2.3 / only 1.2.x / exactly that / at least / anything

Installing & Removing Packages

npm installInstall everything listed in package.json (npm i)
npm install lodashAdd a package to dependencies
npm install -D prettierAdd to devDependencies (--save-dev)
npm install lodash@4.17.21 @latest @^4A specific version / the newest / a range or tag
npm install --save-exact lodashRecord the exact version, not a ^ range
npm install -g <pkg>Install globally (a command-line tool). Add --dry-run to see what would happen
npm install --omit=devSkip dev dependencies (for a production install)
npm uninstall lodashRemove a package
npm updateMove packages up within the ranges in package.json
npm ciA clean, exact install from package-lock.json; deletes node_modules first; used in automated builds
npm prune npm dedupe npm rebuildRemove extras / flatten duplicates / rebuild native add-ons

Running Scripts & Tools

npm run <name>Run a script from package.json; plain npm run lists them
npm run <name> -- --flag valueEverything after -- is passed to the script
npm start npm testShortcuts for the start and test scripts (npm start defaults to node server.js if that file exists)
npm run --if-present <name>Do nothing instead of failing when the script does not exist
pre<name> post<name>Scripts that run before / after another (such as predev, prebuild: your Astro site uses these)
npx <tool> npm exec -- <tool>Run a package's command, installing it temporarily if needed; --yes skips the prompt
npm create <name>Run a project generator, such as npm create astro@latest
node_modules/.binWhere project tools live; npm scripts find them automatically

Looking Around

npm ls --depth=0Top-level installed packages; npm ls -g --depth=0 for global ones
npm outdatedWhich packages have newer versions (current, wanted, latest)
npm explain <pkg>Why a package is installed: the chain that needs it
npm view <pkg> version versions --jsonFacts about a package on the registry
npm search <words>Search the registry
npm docs <pkg> npm repo <pkg>Open its home page / repository
npm fundWhich packages ask for funding
npm pack --dry-runList what would be in the published package
npm query ':root'Search the dependency tree with selectors
npm root npm root -g npm prefixWhere local / global packages live; the project root
npm ping npm whoami npm doctorCheck the registry connection / who you are logged in as / the health of the setup

Security & the Lock File

package-lock.jsonRecords the exact version of every package; commit it so everyone gets the same tree
npm auditReport known vulnerabilities in your dependencies
npm audit fixApply safe fixes; add --dry-run first, and treat --force as risky because it can jump major versions
npm installNever edit node_modules by hand: it is rebuilt from the lock file
ignore-scriptsA setting (false here) that stops packages running their install scripts; npm config set ignore-scripts true turns it on, and some packages then need npm rebuild
Choose packages with careCheck the publisher, download counts, last update and the exact spelling: look-alike names are used to spread malware

npm Configuration

npm config list npm config list -lYour settings / every setting with its default
npm config get <key> set deleteRead, change or remove a setting
.npmrcA settings file: project (next to package.json), user (~/.npmrc), global, and the built-in one; project wins over user
registry @scope:registryWhere to download packages; a different registry just for one scope
save-exact=trueIn .npmrc: always record exact versions
fund=false audit=falseSwitch off the funding message / the audit on install
npm cache verifyCheck and tidy the cache (here under C:\Users\emuba\AppData\Local\npm-cache)
npm help <command>The manual for a command

Versions & Updating

npm install -g npm@latestUpdate npm itself (my knowledge)
winget install OpenJS.NodeJS.LTSInstall or update the Long Term Support Node with winget (the package id is from my knowledge)
nvm-windows fnm VoltaTools that install several Node versions side by side; none is installed here
engines .nvmrcRecord which Node version a project wants
LTS or Current?Use an LTS (even-numbered) release for real work; Current releases are for trying new features
corepack enableTurn on pnpm and Yarn shims that ship with Node

Debugging & Profiling

JavaScript Debug TerminalVS Code command: a terminal where any node you start is debugged automatically
node --inspect-brk app.jsPause on the first line; attach from VS Code or chrome://inspect
launch.json type nodeSee the VS Code Debugging sheet (program, skipFiles)
console.table(x) console.dir(x, {depth: null})Readable output of arrays and deeply nested objects
console.time('x') console.timeEnd('x')Time a block
node --cpu-prof app.jsProduces a .cpuprofile file you can open in VS Code or Chrome DevTools

Habits Worth Having (my suggestions)

Ignore node_modulesAdd node_modules/ to .gitignore; never commit it
Commit package-lock.jsonAnd use npm ci when you want an exact copy
Script the routinePut dev, build, test and lint in scripts so everyone uses the same commands
Pin the Node versionUse engines (and .nvmrc if you add a version manager)
Update regularlyRun npm outdated now and then; small updates are easier than big ones
"npm.ps1 cannot be loaded because running scripts is disabled"
In Windows PowerShell, typing npm can run the npm.ps1 script, which the execution policy may block. Fix it for your account with Set-ExecutionPolicy RemoteSigned -Scope CurrentUser (see the Python Environments and PowerShell sheets), or type npm.cmd instead, or use a Command Prompt or WSL terminal.
Common npm errors and what to try
ERESOLVE (conflicting peer dependencies): read which two packages disagree, update one, or as a last resort add --legacy-peer-deps. EACCES (permission denied): avoid sudo npm; fix the folder permissions or use a user-level prefix. Cannot find module: run npm install, then check the path, the file extension and whether you used require in an ES module (or the reverse). EADDRINUSE: something already uses the port; on Windows find it with Get-NetTCPConnection -State Listen. Strange behaviour after changing branches: delete node_modules and run npm ci.
node_modules inside OneDrive
Your projects live in a OneDrive folder, and node_modules can hold tens of thousands of small files that OneDrive will try to sync, which can be slow. Consider keeping heavy projects outside OneDrive, or telling OneDrive to skip the node_modules folder. (This is a general observation, not something I tested on your machine.)