JS
Node.js
What is Node.js?
Node.js is an open-source, cross-platform, JavaScript runtime environment that executes JavaScript code outside a web browser. Node.js lets developers use JavaScript to write command-line tools and for server-side scripting—running scripts server-side to produce dynamic web page content before the page is sent to the user's web browser.
Installation
Windows
# Download and install Chocolatey:
powershell -c "irm https://community.chocolatey.org/install.ps1|iex"
# Download and install Node.js:
choco install nodejs --version="22.21.1"
# Change PowerShell security policy
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
# Verify the Node.js version:
node -v # Should print "v22.21.1".
# Verify npm version:
npm -v # Should print "10.9.4".
NPM
npm (Node Package Manager) is the default package manager bundled with Node.js. It combines a registry of public and private packages with a CLI that handles project bootstrap, dependency resolution, scripts, and security features. A full command reference is available in the official docs.
Core Concepts
package.json– declares project metadata, dependencies, scripts, and engines. Runnpm initto scaffold it.package-lock.json– captures the exact dependency tree to reproduce installs across environments.node_modules/– on-disk cache of installed packages; regenerate it withnpm installfrom the lockfile.- Semantic versioning – ranges such as
^1.4.0(any non-breaking update) or~1.4.0(only patch updates) control how npm resolves versions.
Mirror
Option 1:
> npm config set registry https://registry.npmmirror.com
Option 2:
Alternatively, you can set the registry in the global .npmrc configuration file:
> nano ~/.npmrc
Add the following line:
registry=https://registry.npmmirror.com
Verify
To verify the change, run:
> npm config get registry
Project Setup
Initialize a new package manifest:
> npm init
Use npm init -y to accept defaults in non-interactive scenarios. After editing package.json, install all declared dependencies via:
> npm install
Installing Dependencies
> npm install <package_name>
With verbose output:
> npm install <package_name> --verbose
- Add to devDependencies:
npm install --save-dev <package_name> - Install a specific version:
npm install <package_name>@1.2.3 - Global utilities (e.g., CLIs):
npm install -g <package_name>
Updating and Removing
- Update all direct dependencies to the latest allowed by semver:
npm update - Targeted update:
npm update <package_name> - Remove packages:
npm uninstall <package_name> - Clean unused packages from
node_modules:npm prune - Deduplicate nested dependencies when possible:
npm dedupe
Scripts and Tooling
Define scripts in package.json:
"scripts": {
"build": "tsc -p .",
"lint": "eslint .",
"test": "npm run lint && vitest"
}
Run with:
> npm run build
> npm run test -- --watch
Use npx <binary> to execute a project-local CLI without a global install.
Security and Quality Checks
- Identify vulnerable dependencies:
npm audit - Attempt automatic fixes:
npm audit fix - Detect outdated packages:
npm outdated - Lock down dependency versions before publishing:
npm shrinkwrap
Version Management
Use semantic versioning so consumers can reason about compatibility:
- MAJOR (
npm version major) – introduce breaking changes; results in2.0.0 -> 3.0.0. - MINOR (
npm version minor) – add backward-compatible features;2.1.4 -> 2.2.0. - PATCH (
npm version patch) – bug fixes and small improvements;2.1.4 -> 2.1.5. - Prerelease builds:
npm version prerelease --preid=betaturns2.1.4into2.1.5-beta.0.
npm version updates package.json, package-lock.json, and creates a git tag. Pass --no-git-tag-version when you only want to bump the manifest. Ensure the repository is clean so the command can commit/tag atomically before publishing.
Publishing to npmjs.com
- Create and secure an npm account at npmjs.com. Enable two-factor authentication (2FA) for both login and publishing actions (
npm profile enable-2fa auth-and-writes) to protect your packages. - Authenticate via CLI:
npm login. Usenpm login --registry=https://registry.npmjs.org/if a custom registry is configured locally. - Prepare package metadata:
- Ensure
name,version,description,repository, andlicensefields exist inpackage.json. - For scoped packages (
@scope/pkg), set"publishConfig": { "access": "public" }if the scope defaults to private. - Add
.npmignore(or usefileswhitelist) to remove build artifacts and secrets from the tarball.
- Ensure
- Versioning: follow semver and bump using
npm version patch|minor|majorwhich updatespackage.json,package-lock.json, and tags git by default. - Dry run builds/tests via scripts such as
npm run lint && npm test. Use theprepublishOnlyscript hook to guarantee the package is validated before publishing. - Publish:
> npm publish- For scoped packages that should be private (requires paid org), add
--access=restricted. - Use
npm publish --tag betato release prerelease builds without replacinglatest.
- For scoped packages that should be private (requires paid org), add
- Post-release maintenance:
- Manage dist-tags:
npm dist-tag add <package>@<version> latest. - Deprecate older versions with a message if necessary:
npm deprecate <package>@<range> "Reason". - If a publish must be undone, use
npm unpublish <package>@<version>promptly (within npm’s time limits) or deprecate instead for stability.
- Manage dist-tags:
Cache
Clear Cache
> npm cache clean --force
Verify cache integrity if installs behave unexpectedly:
> npm cache verify
Troubleshooting
node : 无法将“node”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。
This error occurs when the Node.js executable is not in the system PATH. To fix this issue, add the Node.js installation directory to the system PATH.
npm : 无法加载文件 npm.ps1,因为在此系统上禁止运行脚本。This error occurs when the PowerShell execution policy is set to
Restricted. To fix this issue, run the following commands:
> Get-ExecutionPolicy
> Set-ExecutionPolicy -Scope CurrentUser
Enter RemoteSigned when prompted, then restart PowerShell so the npm shim scripts can run.