Skip to content

Interview PrepProcess and packages · Basics

npm and Packages ​

73. What is package.json, and what information does it contain? ​

The short answer

package.json is the manifest of a Node.js project or package. It names the project and its version, lists the packages it depends on with allowed version ranges, defines scripts such as build, start and lint, says whether .js files are ES modules or CommonJS through type, declares the entry points other code imports through main or exports, and records requirements such as the supported Node.js versions. npm reads it to install dependencies and run scripts.

json
{
  "name": "shop-api",
  "version": "2.4.1",
  "private": true,
  "type": "module",
  "engines": { "node": ">=24" },
  "scripts": {
    "dev": "node --watch --env-file=.env src/server.ts",
    "build": "tsc -p tsconfig.build.json",
    "start": "node dist/server.js",
    "lint": "eslint ."
  },
  "dependencies": {
    "express": "^5.1.0",
    "pg": "^8.13.0",
    "zod": "^3.24.0"
  },
  "devDependencies": {
    "typescript": "^5.9.0",
    "eslint": "^9.20.0"
  }
}
FieldMeaning
name, versionIdentity; required to publish
private: trueStops accidental publishing to the registry
type"module" makes .js files ES modules (question 69)
enginesSupported Node.js versions
scriptsCommands run with npm run <name>
dependencies, devDependenciesWhat to install (question 75)
peerDependenciesWhat the host project must provide (question 80)
main, exportsWhat other code gets when it imports this package
binCommand-line tools the package provides
filesWhat is included when the package is published
workspacesSeveral packages in one repository

74. What is package-lock.json, and why should it be committed? ​

The short answer

package-lock.json records the exact version of every installed package, including dependencies of dependencies, with where it was downloaded from and a hash of its contents. package.json only says ranges such as ^5.1.0; the lockfile pins what was actually installed. Committing it means every developer, every CI run and every production build installs exactly the same tree, so "works on my machine" bugs from silent upgrades disappear, and the hashes protect against tampered downloads.

json
"node_modules/express": {
  "version": "5.1.0",
  "resolved": "https://registry.npmjs.org/express/-/express-5.1.0.tgz",
  "integrity": "sha512-...",
  "dependencies": { "body-parser": "^2.2.0", "...": "..." }
}

What happens without it: ^5.1.0 allows any 5.x version. A new release of a sub-dependency published last night is installed in today's build, and if it has a bug, production breaks with no code change of yours.

package.jsonpackage-lock.json
Written byYou, and npm when you add packagesnpm
ContainsDirect dependencies with rangesThe full tree, exact versions, hashes
Commit itYesYes
Used by npm ciTo check it matches the lockAs the exact install plan (question 79)

Libraries publish without their lockfile: a lockfile only affects the project where npm install runs, so a library's users get versions resolved in their own project.

75. What is the difference between dependencies and devDependencies? ​

The short answer

dependencies are packages your code needs when it runs in production, such as Express, a database driver or Zod. devDependencies are packages needed only to develop and build, such as TypeScript, ESLint, type definitions and build tools. Production installs can skip dev dependencies with npm ci --omit=dev, which makes images smaller and reduces the code attackers could exploit. When you publish a library, only its dependencies are installed for its users.

bash
npm install express          # adds to dependencies
npm install -D typescript    # adds to devDependencies
npm ci --omit=dev            # production install without dev tools
Put in dependenciesPut in devDependencies
Web framework, database drivers, validationTypeScript, @types/*
Logging, HTTP clientsESLint, Prettier
Anything imported by the running appBuild tools, bundlers, code generators

A common mistake in Docker builds: running npm ci --omit=dev before npm run build fails, because TypeScript is a dev dependency. Use a multi-stage build: install everything and build in the first stage, then install only production dependencies in the final image.

76. What is semantic versioning? ​

The short answer

Semantic versioning writes versions as MAJOR.MINOR.PATCH, such as 5.1.2. A patch increase means bug fixes only, a minor increase means new features that do not break existing code, and a major increase means breaking changes. In package.json, a caret, ^5.1.2, allows newer minor and patch versions but not a new major one, and a tilde, ~5.1.2, allows only newer patch versions. The lockfile then pins the exact version actually used.

RangeAllowsExample match
5.1.2Exactly that5.1.2
~5.1.2Patches5.1.9, not 5.2.0
^5.1.2Minors and patches5.9.0, not 6.0.0
^0.4.2Patches only, below 1.00.4.9, not 0.5.0
>=24That or newerCommon in engines
5.2.0-beta.1A pre-releaseOnly when asked for

The 0.x exception. Before 1.0.0, semver treats every minor version as possibly breaking, so ^0.4.2 behaves like ~0.4.2.

Semver is a promise, not a guarantee. A library can ship a breaking change in a minor version by mistake. That is why the lockfile, reviewing upgrade changelogs, and automated dependency update tools such as Dependabot or Renovate, with CI checks on each update, matter.

77. What is npm, and how does it work? ​

The short answer

npm is Node.js's package manager and the public registry behind it. The command-line tool reads package.json and the lockfile, works out a dependency tree that satisfies all version ranges, downloads each package's tarball from the registry, verifies its hash, unpacks it into node_modules, runs install scripts, and writes the lockfile. It also runs project scripts, publishes packages and checks for known vulnerabilities. Alternatives such as pnpm and Yarn use the same registry with different install strategies.

What npm install does, step by step:

  1. Read package.json and package-lock.json.
  2. Resolve a version for every package and sub-package that satisfies all ranges, reusing the lockfile where it is valid.
  3. Fetch tarballs from the registry, or from the local cache (question 82).
  4. Verify each tarball against the integrity hash.
  5. Place packages in node_modules, flattened where possible (question 85).
  6. Run lifecycle scripts such as postinstall.
  7. Write the updated lockfile.

Install scripts are a security risk. A postinstall script runs arbitrary code on your machine or CI runner at install time, and several supply-chain attacks used exactly this. Some teams install with --ignore-scripts in CI and allow scripts only for packages that need them.

ToolNotable difference
npmBundled with Node.js
pnpmStores each version once on disk and links it; strict, no access to undeclared packages; fast
YarnWorkspaces, an alternative install mode without node_modules

78. What is npx, and when would you use it? ​

The short answer

npx runs a command from an npm package without installing it globally. If the package is in your project's node_modules, it runs that local version; otherwise it downloads the package to a cache and runs it. Use it for one-off tools and project generators, such as npx create-vite@latest, and to run your project's local tools with the exact version the project pins. Be careful with spelling, because running a mistyped package name can download and run someone else's code.

bash
npx create-vite@latest shop-web --template react-ts     # a generator, used once
npx tsc --noEmit                                        # the project's own TypeScript version
npx autocannon -c 50 http://localhost:3000              # a tool you need occasionally

Why not install tools globally? A global install is one version for every project on the machine, which drifts and conflicts. A local dev dependency run with npx, or through an npm run script, gives each project its own pinned version.

79. What is the difference between npm install and npm ci? ​

The short answer

npm install is for development: it installs what package.json asks for, may update package-lock.json when ranges allow newer versions or you add packages, and keeps the existing node_modules. npm ci is for automated builds: it deletes node_modules, installs exactly what the lockfile says, never changes the lockfile, and fails if package.json and the lockfile disagree. That makes CI and Docker builds reproducible, and usually faster.

npm installnpm ci
Source of truthpackage.json, lockfile where validThe lockfile, exactly
Changes the lockfileIt canNever
Existing node_modulesKept and updatedDeleted first
Lockfile out of sync with package.jsonFixes the lockfileFails the build
Use inLocal development, adding packagesCI pipelines, Docker images
dockerfile
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY dist ./dist

Copying only the two manifest files before npm ci lets Docker reuse the cached dependency layer whenever the dependencies have not changed (the Docker layer caching question).

80. What is a peer dependency? ​

The short answer

A peer dependency is a package that your package needs, but expects the project using it to install, so that both share one copy. It is used for plugins and add-ons: a React component library lists react as a peer dependency, because it must use the same React as the app, not a private copy. Since npm 7, peer dependencies are installed automatically, and npm reports an ERESOLVE error when two packages require incompatible versions of the same peer.

json
{
  "name": "@shop/ui",
  "peerDependencies": {
    "react": "^18.0.0 || ^19.0.0"
  }
}

Why not a normal dependency? Two copies of React in one app break hooks and context, because each copy keeps its own internal state. Declaring it as a peer means the library uses the app's single copy.

The ERESOLVE error, and what to do:

OptionWhen
Upgrade the package that has the old peer rangeBest fix, if a newer version exists
Use overrides in package.json to force one versionYou have checked it really works
--legacy-peer-depsA temporary escape hatch; it skips peer checks entirely

81. What does npm audit check? ​

The short answer

npm audit compares every package in your dependency tree, including indirect ones, against a database of known security advisories, and reports which installed versions are affected, how severe the issue is, and which version fixes it. npm audit fix upgrades within allowed ranges where it can. It only knows about vulnerabilities that have been reported; it does not detect new malicious packages or check how you use the code. npm audit signatures separately checks that packages were signed by the registry.

bash
npm audit                       # report
npm audit --omit=dev            # only what ships to production
npm audit fix                   # apply safe upgrades within ranges
npm audit signatures            # verify registry signatures and provenance

Reading results sensibly:

QuestionWhy it matters
Is the vulnerable package in production code or only in dev tools?A dev-only build tool issue is usually lower risk
Is the vulnerable function reachable from your code?Many reports are for features you never use
Is a fixed version available?Upgrade, or override a sub-dependency's version

Audit is one layer. Supply-chain attacks, such as a maintainer account being taken over and a malicious version published, appear before any advisory exists. Pin with the lockfile, update deliberately, limit install scripts, and prefer well-maintained packages. Scanning in pipelines is covered in the pipeline security questions.

82. What is the npm cache, and how can it be managed? ​

The short answer

npm keeps a cache of every package tarball it has downloaded, in a content-addressed folder, usually ~/.npm/_cacache, so later installs of the same versions can skip the network. The cache is checked against integrity hashes, so it is safe to reuse. You rarely need to touch it: npm cache verify checks and tidies it, and npm cache clean --force empties it. In CI, caching the npm cache folder between runs, keyed on the lockfile's hash, speeds up npm ci.

yaml
# GitHub Actions: cache npm downloads between runs
- uses: actions/setup-node@v4
  with:
    node-version: 24
    cache: npm                     # caches ~/.npm, keyed on package-lock.json
- run: npm ci

Cache ~/.npm, not node_modules. npm ci deletes node_modules anyway, and a cached node_modules can contain binaries built for a different platform.

83. What are globally installed npm packages? ​

The short answer

A global package, installed with npm install -g, goes into one shared location on the machine instead of the project's node_modules, and its command-line tools are added to your PATH, so you can run them from anywhere. It suits personal tools you use across all projects. For project tools, prefer local dev dependencies run through npm run or npx, so every developer and CI uses the same version.

bash
npm install -g npm-check-updates     # a personal tool
npm ls -g --depth=0                  # list global packages
npm prefix -g                        # where they are installed
GlobalLocal dev dependency
Version shared byEvery project on the machineThis project only
Recorded in the repositoryNoYes, in package.json and the lockfile
Same on CIOnly if installed there tooYes

Permission errors when installing globally on Linux or macOS usually mean the global folder belongs to root. Use a Node.js version manager, such as nvm, fnm or Volta, which installs global packages in your home folder, rather than sudo npm.

84. How do you publish an npm package? ​

The short answer

Prepare package.json with a unique name, a version, the exports and types entry points and a files list so only the built output is published. Build it, check the contents with npm pack --dry-run, bump the version with npm version patch, minor or major, and run npm publish, adding --access public for a scoped public package. Protect the account with two-factor authentication, and prefer publishing from CI with trusted publishing and provenance, which links each release to the exact source commit and build.

json
{
  "name": "@shop/money",
  "version": "1.3.0",
  "type": "module",
  "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" } },
  "files": ["dist"],
  "license": "MIT"
}
bash
npm run build
npm pack --dry-run          # (1) list exactly what would be published
npm version minor           # (2) 1.3.0 → 1.4.0, with a git tag
npm publish --access public # (3)
  1. Check the contents: no .env, no source maps you did not intend, no test fixtures.
  2. npm version updates package.json, commits and tags.
  3. Publish to the registry.

From CI, with trusted publishing:

yaml
permissions:
  id-token: write                       # lets the job prove its identity to npm
steps:
  - run: npm ci && npm run build
  - run: npm publish --provenance --access public

The registry trusts this specific repository and workflow, through OIDC, instead of a long-lived token stored as a secret, and provenance records which commit and workflow built the package. After several supply-chain attacks on npm in 2025, the registry has been moving publishers away from long-lived tokens towards this model.

85. What are tree shaking and package hoisting? ​

The short answer

Tree shaking is a bundler removing code that is exported but never imported, so the final bundle only contains what is used; it works with ES modules, whose imports are visible without running the code, and packages can help by declaring "sideEffects": false. Package hoisting is npm installing dependencies of dependencies at the top level of node_modules when versions allow, instead of nesting them, so each version is stored once; a side effect is that your code can accidentally import a package it never declared.

Tree shaking:

ts
// utils.ts
export function formatPence(p: number) { return `£${(p / 100).toFixed(2)}` }
export function heavyCsvExport(rows: unknown[]) { /* 40 KB of code */ }

// app.ts
import { formatPence } from './utils.js'      // heavyCsvExport is removed from the bundle

It fails when a module does work at import time, such as registering something globally, because the bundler must keep it. That is what "sideEffects" in package.json tells the bundler about.

Hoisting:

text
node_modules/
  express/                 your direct dependency
  body-parser/             hoisted: a dependency of express
  debug/                   hoisted: used by several packages
  some-lib/
    node_modules/
      debug/               nested: some-lib needs a different version

The "phantom dependency" problem. Because debug is hoisted, import debug from 'debug' works in your code even though you never added it to package.json. When express later stops depending on it, your build breaks. pnpm prevents this by giving each package access only to what it declares.

86. How do you investigate and resolve dependency conflicts? ​

The short answer

Find out who wants what: npm ls <package> shows every version installed and which packages pulled each in, and npm explain <package> shows the chain of dependents. Then fix the cause: upgrade the package that requires an old version, align your own direct dependencies, run npm dedupe to collapse duplicates, and only as a last resort use overrides in package.json to force one version, after checking it works. Commit the resulting lockfile.

bash
npm ls zod                     # every installed zod version, and who needs it
npm explain zod                # why each version is there
npm outdated                   # what has newer versions
npm dedupe                     # reduce duplicate copies where ranges allow

A typical case: your app uses zod@4, but an internal library still requires zod@3, so two copies are installed and schemas from one are not recognised by the other.

FixWhen
Upgrade the library to a version that accepts zod@4Best: removes the conflict
Ask its maintainers, or contribute the upgradeThe library has no compatible release yet
"overrides": { "zod": "^4.0.0" }You have checked the library works with it
Keep both versionsThey do not need to share objects

Peer dependency conflicts show up as ERESOLVE errors at install time (question 80). Resolve them the same way: upgrade first, override carefully, and avoid leaving --legacy-peer-deps in your scripts for ever.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Node.js
Runtime
Memory and debugging
Data and files
Process and packages
Other topics
Nothing picked yet