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 versionnpm doctorReports that newer versions exist (npm 12.2.0 and Node 24.21.0 at the time of writing); everything else checked was finenpm root -gGlobal packages live in C:\Users\emuba\AppData\Roaming\npm; the only global package is @anthropic-ai/claude-codenpm 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 themNot installedpnpm, Yarn, nvm, fnm and Volta (no Node version manager); Bun and Deno are absent tooastro-siteYour site's package.json asks for Node 22.12 or newer (engines), which 24.18 satisfiesRunning Node
node file.js a bRun a file; the extra words arrive in process.argv.slice(2)nodeWith no file: the interactive REPLnode -e "code" node -p "expression"Run code from the command line / run an expression and print the resultnode --watch file.jsRestart whenever the file (or what it imports) changes; --watch-path=src chooses folders. Not combinable with -enode --env-file=.env file.jsLoad variables from a file into process.env; --env-file-if-exists does not fail if the file is missingnode --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 runningnode --testRun test files with the built-in runner; --test-reporter=spec and --experimental-test-coverage worknode -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 kindnode --inspect --inspect-brkAllow a debugger to connect / also stop on the first linenode --cpu-prof --heap-profWrite CPU or memory profiles for later analysisnode --permission --allow-fs-read=*Run with the permission model: file, network and process access is denied unless allowednode --helpAll optionsThe 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 expressionTabComplete names; press twice to list the options.exit Ctrl+D Ctrl+C twiceLeave the REPLModules: ESM and CommonJS
import fs from 'node:fs'ES module syntax; the node: prefix marks a built-inconst 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 saysimport.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 modulesawait import('./x.js')Load a module while the program runs; top-level await works in ES modulesmodule.exports = … export default …Share a value from a fileimport 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, URLsnode:http node:httpsServers and requestsnode:cryptoHashes, random bytes, encryptionnode:child_processRun other programsnode:readline node:events node:stream node:utilRead input a line at a time / events / streams / helpersnode:test node:assertThe built-in test runner and assertionsnode:worker_threads node:zlib node:timers/promisesThreads / compression / await-able timersnode: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 globals72 built-in modulesThat is how many this version lists in require('module').builtinModulesThe 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 hereprocess.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+Cprocess.memoryUsage() process.uptime()Memory and running timeprocess.versionsVersions of Node and its parts (V8, OpenSSL, SQLite…)process.stdin process.stdoutStandard input and output streamspackage.json Essentials
npm init -yCreate a package.json with defaultsname 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 testpeerDependencies optionalDependenciesPackages the user must supply / nice to havemain exports binEntry file / public entry points / commands the package installstypemodule or commonjsenginesVersions of Node (and npm) that the project supports, e.g. { "node": ">=22.12.0" }privatetrue prevents publishing by accidentfilesWhat goes into the package when publishedworkspacesSeveral packages in one repositoryoverridesForce a version of a dependency anywhere in the treenpm 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 / anythingInstalling & Removing Packages
npm installInstall everything listed in package.json (npm i)npm install lodashAdd a package to dependenciesnpm install -D prettierAdd to devDependencies (--save-dev)npm install lodash@4.17.21 @latest @^4A specific version / the newest / a range or tagnpm install --save-exact lodashRecord the exact version, not a ^ rangenpm install -g <pkg>Install globally (a command-line tool). Add --dry-run to see what would happennpm install --omit=devSkip dev dependencies (for a production install)npm uninstall lodashRemove a packagenpm updateMove packages up within the ranges in package.jsonnpm ciA clean, exact install from package-lock.json; deletes node_modules first; used in automated buildsnpm prune npm dedupe npm rebuildRemove extras / flatten duplicates / rebuild native add-onsRunning Scripts & Tools
npm run <name>Run a script from package.json; plain npm run lists themnpm run <name> -- --flag valueEverything after -- is passed to the scriptnpm 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 existpre<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 promptnpm create <name>Run a project generator, such as npm create astro@latestnode_modules/.binWhere project tools live; npm scripts find them automaticallyLooking Around
npm ls --depth=0Top-level installed packages; npm ls -g --depth=0 for global onesnpm outdatedWhich packages have newer versions (current, wanted, latest)npm explain <pkg>Why a package is installed: the chain that needs itnpm view <pkg> version versions --jsonFacts about a package on the registrynpm search <words>Search the registrynpm docs <pkg> npm repo <pkg>Open its home page / repositorynpm fundWhich packages ask for fundingnpm pack --dry-runList what would be in the published packagenpm query ':root'Search the dependency tree with selectorsnpm root npm root -g npm prefixWhere local / global packages live; the project rootnpm ping npm whoami npm doctorCheck the registry connection / who you are logged in as / the health of the setupSecurity & the Lock File
package-lock.jsonRecords the exact version of every package; commit it so everyone gets the same treenpm auditReport known vulnerabilities in your dependenciesnpm audit fixApply safe fixes; add --dry-run first, and treat --force as risky because it can jump major versionsnpm installNever edit node_modules by hand: it is rebuilt from the lock fileignore-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 rebuildChoose packages with careCheck the publisher, download counts, last update and the exact spelling: look-alike names are used to spread malwarenpm Configuration
npm config list npm config list -lYour settings / every setting with its defaultnpm 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 userregistry @scope:registryWhere to download packages; a different registry just for one scopesave-exact=trueIn .npmrc: always record exact versionsfund=false audit=falseSwitch off the funding message / the audit on installnpm cache verifyCheck and tidy the cache (here under C:\Users\emuba\AppData\Local\npm-cache)npm help <command>The manual for a commandVersions & 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 hereengines .nvmrcRecord which Node version a project wantsLTS or Current?Use an LTS (even-numbered) release for real work; Current releases are for trying new featurescorepack enableTurn on pnpm and Yarn shims that ship with NodeDebugging & Profiling
JavaScript Debug TerminalVS Code command: a terminal where any node you start is debugged automaticallynode --inspect-brk app.jsPause on the first line; attach from VS Code or chrome://inspectlaunch.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 objectsconsole.time('x') console.timeEnd('x')Time a blocknode --cpu-prof app.jsProduces a .cpuprofile file you can open in VS Code or Chrome DevToolsHabits Worth Having (my suggestions)
Ignore node_modulesAdd node_modules/ to .gitignore; never commit itCommit package-lock.jsonAnd use npm ci when you want an exact copyScript the routinePut dev, build, test and lint in scripts so everyone uses the same commandsPin 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.)