npm from Zero: Initialise a Project, Write Scripts, Install Packages, Pack — in One Pass
npm ships with Node.js, but most people only ever type npm install. This guide starts from zero: npm init to create package.json, scripts to store commands, how npm install works with the lockfile, npm pack to check before publishing — plus npx, npm ci, and the upgrade trio. Every step was run for real on Node.js v24.22.1 and npm 10.9.4; the transcript is included.

Almost everyone who writes anything with Node.js deals with npm every day: installing a package, running a script, shipping a version. But "using it every day" and "actually knowing it" are two different things. Many people's understanding of npm stops at "npm install installs packages", and when they hit "why does it run on my colleague's machine but not mine" or "why does the lockfile always conflict", the only fix they know is deleting node_modules and reinstalling and hoping. This guide starts from zero: initialise a project, write scripts, install a package, inspect dependencies, pack it — every step run for real in a live environment, with the output in the test record at the end. The environment here is Node.js v24.22.1 and npm 10.9.4, against the default registry, registry.npmjs.org.
First, what npm is. It is the package manager that ships with Node.js, and it does three things: download packages other people wrote from a registry, manage the versions of those packages for you, and give you a scripting mechanism so common operations run with a single command. Its core file is package.json: a project's ID card and instruction manual in one — name, version, dependencies, and scripts all live there. The key to understanding npm is one sentence: package.json is the source of truth, and node_modules is only the result of executing it. When something goes wrong, look at package.json first, then node_modules — never the other way round.
1. Starting from zero: npm init creates your first package.json
Create an empty directory and run npm init -y, and npm immediately generates a package.json. The -y means "take all the defaults, don't ask me one by one". In our test run the defaults were: the name taken from the directory (here demo276-npm), version 1.0.0, the entry point main set to index.js, and the license set to ISC. One default is worth noticing: scripts already contains a test script, echo "Error: no test specified" && exit 1 — meaning "you have not written a test yet, so running tests fails". That default surprises a lot of first-timers; it is not a bug, it is npm reminding you that testing is your job.
Without -y, npm asks you one question at a time: package name, version, description, entry point, test command, repository, keywords, author, licence. Walking through it interactively once is a good way to build an intuition for what each field does. But in daily work, -y plus editing afterwards is faster. There are two ways to edit package.json: edit the file directly, or use the npm pkg set command. In our test we used npm pkg set scripts.hello="node app.js" scripts.test="node app.js", changing two script fields in one go. The advantage of this approach is that you cannot break the JSON — the most common accident when editing JSON by hand is a missing comma, after which the whole file fails to parse.
A few more package.json fields are worth knowing. name and version together are the package's unique identity on the registry; main tells others "load this file first when requiring this package"; keywords are for registry search; license declares the licence. When you are starting out, you do not need to memorise every field — name, version, scripts, and dependencies are enough; look the rest up when you meet them.
2. scripts: store the commands you type every day
scripts is the most underrated feature in npm. At its core it gives shell commands names: write "hello": "node app.js" in package.json, and from then on npm run hello executes node app.js in the project root. In our test run, npm run hello printed three layers: "demo276-npm@1.0.0 hello", then "node app.js", then "hello npm demo 276". The first line is npm telling you which package and which script it is running, the second is the command itself, the third is the command's own output. Once you can read that three-layer structure, no npm output will confuse you again.
Some scripts have built-in shortcuts, so you can run them without writing run: npm test runs the test script, npm start runs the start script, npm stop runs the stop script. In our test, npm test printed the same "hello npm demo 276" as npm run hello, because we had set the test script to node app.js as well. One detail: npm test, npm start, and friends are still npm run underneath — they just save you three letters. Agree on a convention in your team; do not agonise over which spelling to use.
scripts has two more advanced uses that are in the official docs and used rarely in daily work, but knowing them saves trouble. First, pre and post: define a myscript, then define premyscript and postmyscript, and running npm run myscript executes all three in "before, main, after" order. A typical use is running a lint check in pretest and cleanup in posttest. Second, lifecycle scripts: prepare, prepack, postpack, and friends are reserved names that npm triggers automatically at specific moments of npm install, npm pack, and npm publish. For example, prepare runs before packing, which is where build tasks like compiling TypeScript belong. The official docs put it plainly: "Try not to use scripts to do what npm can do for you" — read through the package.json field reference first, because many needs do not require a script at all.
Two more environment details about how scripts run are worth knowing. First, npm adds node_modules/.bin to the script's PATH, which means you can call executables that your dependencies provide directly by name — install TypeScript and you can write tsc in a script, without the ./node_modules/.bin/tsc prefix. Second, npm passes some of package.json's information to the script as environment variables, for example npm_package_name for the package name and npm_package_version for the version, readable in a script as process.env.npm_package_name. There is also INIT_CWD, which records the directory you were in when you typed npm run — because scripts always run from the project root, INIT_CWD is how a script can learn "which subdirectory the user ran from". The official docs state it directly: "Scripts are always run from the root of the package folder, regardless of what the current working directory is when you invoke npm." That guarantee lets a script safely assume it is running at the project root.
3. Installing packages: how npm install and the lockfile work together
Installing a package is the most common npm operation, and in our test we installed a small package: npm install is-odd@3.0.1 --save-exact. Breaking down the syntax: is-odd is the package name, @3.0.1 pins the version, and --save-exact means "write the version into package.json exactly as given, without a range operator like ^". The output was "added 2 packages in 925ms" — two packages, because is-odd itself depends on another small package, is-number. 962 milliseconds is the total time to download and unpack from the registry; small packages are that fast.
After installing, three things changed. First, package.json gained a line in dependencies: "is-odd": "3.0.1". Second, a node_modules folder appeared in the project root, containing the code for is-odd and is-number. Third, a package-lock.json appeared, recording the exact version and download address of every package. To verify, run node -e "console.log(require('is-odd')(7), require('is-odd')(8))" — it prints true false, confirming the package loads. Then run npm ls --depth=0, which prints demo276-npm@1.0.0 with is-odd@3.0.1 underneath — the current project's top-level dependency list.
The division of labour between package.json and package-lock.json is the thing beginners confuse most. The official docs are clear: package.json is the source of the "acceptable version range", and package-lock.json is the record of "which exact version was actually installed". When you run npm install with no arguments, npm compares the two files: if the lockfile's versions satisfy the ranges in package.json, it installs the lockfile's exact versions, so every install produces the same result; if the ranges do not match — say you changed ^7.0.0 to ^8.0.0 — npm resolves new versions that satisfy the new range and updates the lockfile. In other words, package.json is the rule, and the lockfile is the execution record. In team work, the lockfile must be committed to version control, or "works on my machine" problems multiply.
Another common question: npm install with no arguments and npm install with a package name are two different operations. With no arguments it means "install everything package.json and the lockfile say should be here"; with a package name it means "install one new package, and record it in package.json". The first restores an environment; the second adds a dependency. When you pick up a project, run the no-argument install first; when you want to add a feature, run the one with a package name. Doing them in the wrong order produces "ghost dependencies" that are installed but recorded nowhere.
4. Packing: npm pack lets you look before you publish
npm pack bundles your project into a tarball (a .tgz file) — the step just before publishing to the registry. Adding --dry-run shows you the list without actually creating the file, which is the right way to check "is the right stuff going into the package". In our test, npm pack --dry-run listed two files: app.js at 35 bytes and package.json at 268 bytes, 307 bytes in total, with the filename demo276-npm-1.0.0.tgz. The output also carries verification data: the shasum and integrity lines, which let anyone check that the package contents have not been tampered with.
This command is valuable because it lets you "look first". A common way beginners break their first npm publish is packing things that should not be there (test fixtures, local config files) or leaving out things that should (the entry file). Run npm pack --dry-run before publishing and check the file list, and you catch most of those accidents. If node_modules or a .env file shows up in the list, your .npmignore or the files field in package.json needs adjusting — the pack list is your first line of defence.
5. Registries and configuration: you decide where packages come from
By default, npm downloads packages from registry.npmjs.org; run npm config get registry to see the current address — in our test it printed exactly https://registry.npmjs.org/. Developers in China often switch to a mirror: npm config set registry plus the mirror address, or a .npmrc file in the project root. After switching, the install commands stay exactly the same; only the download source changes. Note that switching sources only affects downloads, not where you publish — the publish target registry is configured separately, so do not confuse the two.
The configuration priority is also worth knowing: command-line arguments win, then the .npmrc in the project, then ~/.npmrc in your home directory, and finally npm's built-in defaults. When debugging "why is the install not using the address I expect", check layer by layer in that order and you will almost always find it. npm config list prints all the configuration currently in effect; run it first when a config problem appears, rather than guessing. An .npmrc file is simple — one configuration per line, for example registry=https://registry.npmjs.org/. Put it in the project root and commit it to version control, and everyone on the team uses the same source, with no more "fast for you, slow for me" environment differences.
6. Three traps: the easiest places for beginners to trip
The first trap: running a script that does not exist. In our test, npm run missing-script printed npm error Missing script: "missing-script", exited with code 1, and suggested "to see a list of scripts, run: npm run". The exit code 1 is the key point: many automation pipelines (CI included) judge whether the previous step succeeded by the exit code, and a missing script counts as a failure. Incidentally, npm run with no arguments lists all the scripts in the current project — when you pick up an unfamiliar project, run npm run first; it is more direct than reading package.json.
The second trap: assuming that installing a package means it will run. npm install only downloads and records; it does not check whether the package is compatible with your Node.js version. One detail in the official docs: when you install by name, if the version the latest tag points to is incompatible with the current Node.js version, npm picks the newest compatible version instead; but if you specify a version explicitly, npm installs it as told, and whether it runs is your problem. After installing, spend ten seconds running node -e to require it and confirm it loads — far cheaper than debugging later.
The third trap: installing global packages in the wrong place. npm install -g puts a package globally, which is right for command-line tools (scaffolding tools, for example); project dependencies should never get -g. Dependencies installed globally will not work on another machine; a command-line tool installed locally needs its full path every time. The test is simple: is this package "for the project" or "for the person"? The first goes into dependencies; only the second is a candidate for -g.
7. A complete workflow: from an empty directory to a publishable package
String the commands above together and you get the full flow for a minimal project. Step one: mkdir my-tool && cd my-tool && npm init -y, which gives you a package.json. Step two: write the code — an index.js that exports a function, or an app.js that prints a line, as in our test. Step three: configure scripts with npm pkg set scripts.start="node app.js" scripts.test="node app.js", so npm start launches it and npm test checks it. Step four: install whatever dependencies you need with npm install plus the package name, then check that package.json, package-lock.json, and node_modules all agree. Step five: inspect the pack with npm pack --dry-run and confirm nothing extra got in and the entry file is there. Step six: publish — and before npm publish, confirm you are logged in to the right account and publishing to the right registry, because publishing to the wrong registry is harder to undo than publishing the wrong version.
Every step has a checkpoint: after init, check the name and version in package.json; after configuring scripts, run npm run and look at the list; after installing, run npm ls and check the tree; before packing, check the list. Building the habit of "check at every step" matters more than memorising commands — commands can be looked up, but the ability to locate "which step went wrong" only comes from checkpoints. Once this flow is smooth, version management (npm version), scoped packages (@myorg/package), and private registries all turn out to be extensions of the same skeleton.
8. npx, npm ci, and upgrades: three advanced commands
Once the five basic commands are comfortable, three advanced ones are worth adding. The first is npx: run a package temporarily, without installing it. In our test, npx --yes cowsay "npm demo 276" downloaded cowsay from the registry, printed an ASCII cow saying "npm demo 276", and finished — with no new dependency added to the project. The --yes means "don't ask me, just download it". The typical use of npx is a "use once" tool: run a scaffolding tool once, or run a command from a colleague's project without installing the tool into your own project. The test is: if you will use the tool long-term, npm install it; if once, npx it.
The second is npm ci — the ci stands for continuous integration. Its job is "install strictly from the lockfile": it deletes the whole node_modules directory, then installs exactly the versions in package-lock.json, one by one, without re-resolving version ranges. In our test, npm ci printed "added 2 packages in 452ms", and a following npm ls still showed is-odd@3.0.1 — identical to before. That is the difference from npm install: install looks at the ranges in package.json and may update the lockfile; ci only trusts the lockfile, and errors out if the lockfile and package.json disagree. CI environments, deployment environments, and any time you want to reproduce an install in a clean environment should use npm ci. The official docs say it directly: if you want package.json and the lockfile strictly in sync, use npm ci instead of npm install.
The third is the upgrade trio: npm view, npm outdated, npm update. npm view is-odd version asks the registry directly "what is the latest version of this package" — in our test it returned 3.0.1, confirming we had installed the latest. npm outdated lists every package in the current project that can be upgraded; in our test the output was empty, because is-odd had just been installed at the latest version and there was nothing to upgrade. If the list shows packages, npm update upgrades them within the ranges in package.json — and afterwards, check that package-lock.json moved along. The habit should be: look at outdated first, then decide whether to upgrade; do not run a blanket npm update first thing, because a major-version upgrade can carry breaking changes, and you should read the changelog before upgrading.
9. What to practise next
npm is bigger than this guide, but getting started only needs the main line: npm init to create a project, scripts to store commands, npm install to install packages, npm ls to inspect dependencies, npm pack to check the package. Get those five fluent, then add the three advanced commands from section 8 — npx, npm ci, and the view/outdated/update trio — and the main line is complete. The official docs pages for npm-install and scripts are the main sources for this guide; for anything not covered here, check those two pages directly rather than searching blogs.
Finally, a self-check list — run through it once and you will know whether you really have it: create an empty directory and npm init -y; write an app.js that prints one line; use npm pkg set to configure it as both hello and test scripts; run npm run hello and npm test until both work; install is-odd and confirm that package.json, package-lock.json, and node_modules all agree; look at npm ls; look at the pack list with npm pack --dry-run; then run npm run with a script name that does not exist, and remember what the exit-code-1 error looks like. Once that set runs cleanly, the npm basics are in place. The full output is in the test record demo276_npm_transcript.txt that accompanies this article.
Three more frequently asked questions, the ones beginners ask most. First, can node_modules be deleted? Yes — and it often should be. It is the execution result of package.json and the lockfile, not source code; delete it and one npm install (or npm ci) restores it exactly. Second, what do you do about a package-lock.json conflict? Do not edit it by hand and do not guess: accept one side's version, run npm install once so npm re-resolves, and commit the fresh lockfile. Third, what if an install gets stuck? Check the network first and try another registry mirror; then run npm cache verify to check the local cache; if it still fails, read the last lines of the error — npm's errors usually state the real cause in the final few lines, so do not only look at the warnings scrolling past in the middle.

Comments (0)
Sources
Related articles
cron is the scheduling daemon that has run on Linux for decades: write a crontab file saying 'run this command at this time', and it handles the rest. This guide runs everything for real on Debian cron 3.0pl1-162 — installing a job, waiting one minute for the trigger, verifying the log, removing the job — plus special strings, five classic mistakes, and a real 3 a.m. log-archiving job.
ping does exactly one thing: send an ICMP echo request, wait for the echo reply, and report the round-trip time and packet loss. This guide runs every command for real on iputils ping 20240117 — packet count, interval, quiet mode, packet size, timestamps, IPv4 vs IPv6, the three failure modes, exit codes 0/1/2 — with output pasted verbatim.
cut does one thing: split each line into fields on a delimiter and output the fields you ask for. This guide runs every command for real on GNU coreutils 9.4 — field lists and ranges, CSV and output delimiters, character slicing, --complement, the -s rule for lines without a delimiter, log-column statistics, and the quoted-comma limit — with the output pasted verbatim.