DevToolBoxฟรี
บล็อก

npm install Error: ทุก Error ที่พบบ่อยและวิธีแก้ไข

12 นาทีในการอ่านโดย DevToolBox

Running npm install and hitting a wall of red text is a rite of passage for every JavaScript developer. Whether it is a permissions error on macOS, a dependency conflict in a monorepo, or a corrupted cache in CI, the fix is usually straightforward once you know what to look for. This guide covers every common npm install error, explains why it happens, and gives you the exact commands to fix it.

Error Dictionary: Quick Reference Table

Error CodeWhat It MeansQuick Fix
EACCESPermission denied — npm tried to write to a directory you do not own.Use nvm or fix directory ownership (see below).
ENOENTFile or directory not found — a referenced path does not exist.Delete node_modules and package-lock.json, then reinstall.
EPERMOperation not permitted — often a file lock issue on Windows.Close editors/terminals locking the folder, then retry.
ERESOLVEDependency conflict — two packages require incompatible versions of a peer dependency.Use --legacy-peer-deps or --force (see section below).
ERR_SOCKET_TIMEOUTNetwork timeout — npm could not reach the registry.Check network/proxy settings, or switch to a mirror registry.
code 1A lifecycle script (preinstall, postinstall) exited with error code 1.Check build tools (Python, node-gyp, C++ compiler) are installed.

EACCES: Fixing Permission Errors

This is the most common error on macOS and Linux. It happens when npm tries to install global packages into a system-owned directory like /usr/local/lib/node_modules.

Fix on macOS / Linux (Recommended: Use nvm)

The best permanent fix is to use a Node version manager so npm installs into your home directory:

# Install nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash

# Restart terminal, then install Node
nvm install --lts
nvm use --lts

# Verify — npm now installs to ~/.nvm/
which npm
# /home/youruser/.nvm/versions/node/v20.x.x/bin/npm

Alternative: Change npm default directory manually:

mkdir -p ~/.npm-global
npm config set prefix '~/.npm-global'

# Add to ~/.bashrc or ~/.zshrc:
export PATH=~/.npm-global/bin:$PATH

# Reload shell
source ~/.bashrc

Nuclear option (not recommended for most users):

# NOT recommended — changes system directory ownership
sudo chown -R $(whoami) /usr/local/lib/node_modules
sudo chown -R $(whoami) /usr/local/bin
sudo chown -R $(whoami) /usr/local/share

Fix on Windows

On Windows, run your terminal as Administrator, or better yet, use nvm-windows:

# Install nvm-windows from:
# https://github.com/coreybutler/nvm-windows/releases

# Then in an elevated (Admin) PowerShell:
nvm install lts
nvm use lts

# Or fix npm prefix for current user:
npm config set prefix %APPDATA%\npm

ERESOLVE: Fixing Dependency Conflicts

Starting with npm 7, peer dependency conflicts cause the install to fail by default. You will see a tree diagram showing which packages conflict.

Typical error output:

npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: @some-org/some-package@2.1.0
npm ERR! Found: react@18.2.0
npm ERR! node_modules/react
npm ERR!   react@"^18.2.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.8.0 || ^17.0.0" from some-library@3.5.0
npm ERR! node_modules/some-library
npm ERR!   some-library@"^3.5.0" from the root project

--legacy-peer-deps vs --force

--legacy-peer-deps tells npm to ignore peer dependency conflicts entirely (same behavior as npm 6). --force tells npm to install regardless and accept any potential issues. Here is when to use each:

FlagWhen to Use
--legacy-peer-depsWhen you know the peer dep mismatch is harmless (e.g., React 18 vs 17 peer dep).
--forceWhen you want npm to fetch packages even if a cached copy exists and override conflicts.
# Option 1: Ignore peer deps (safest workaround)
npm install --legacy-peer-deps

# Option 2: Force install (overrides everything)
npm install --force

Preferred approach — pin the conflicting dependency:

// In package.json — add "overrides" to pin the conflicting dep
{
  "overrides": {
    "some-library": {
      "react": "^18.2.0"
    }
  }
}

// Then run:
// npm install

node_modules Corruption: When and How to Nuke and Reinstall

Sometimes node_modules just gets into a bad state. Symptoms include "Cannot find module" errors for packages that are clearly in package.json, or strange build failures after switching branches.

When to Nuke node_modules

  • After switching branches with different dependency trees.
  • After resolving merge conflicts in package-lock.json.
  • When you see "Module not found" for a clearly installed package.
  • After upgrading Node.js to a new major version.

How to Clean Reinstall

Cross-platform one-liner (works in bash):

rm -rf node_modules package-lock.json
npm install

On Windows (PowerShell):

Remove-Item -Recurse -Force node_modules
Remove-Item package-lock.json
npm install

Using npx for convenience:

npx rimraf node_modules
npm install

If problems persist, also clean the npm cache:

npm cache clean --force
rm -rf node_modules package-lock.json
npm install

package-lock.json Conflicts: Merge Strategies

When multiple developers change dependencies, package-lock.json merge conflicts are almost guaranteed. Never try to resolve them manually — the file is machine-generated.

Recommended Merge Strategy

Accept either side of the conflict (it does not matter which):

# Accept "theirs" (the incoming branch's version)
git checkout --theirs package-lock.json
git add package-lock.json

# OR accept "ours" (your branch's version)
git checkout --ours package-lock.json
git add package-lock.json

Regenerate the lock file:

npm install

Commit the result:

git add package-lock.json
git commit -m "chore: regenerate package-lock.json after merge"

Prevent Conflicts with .gitattributes

Add this to your .gitattributes to auto-resolve lock file conflicts:

# .gitattributes
package-lock.json merge=ours

Node.js Version Incompatibility

Many packages require specific Node.js versions. If your Node version is too old (or too new), npm install can fail with compilation errors or unsupported engine warnings.

Check Required Version

Look for the engines field in package.json:

// package.json
{
  "engines": {
    "node": ">=18.0.0",
    "npm": ">=9.0.0"
  }
}

// Check your current version:
// node -v
// npm -v

Use nvm or fnm to Switch Versions

nvm (Node Version Manager):

# List available versions
nvm ls-remote

# Install a specific version
nvm install 20

# Switch to a version
nvm use 20

# Set a default
nvm alias default 20

fnm (Fast Node Manager) — faster alternative:

# Install fnm (Rust-based, faster than nvm)
curl -fsSL https://fnm.vercel.app/install | bash

# Install and use a version
fnm install 20
fnm use 20
fnm default 20

Create an .nvmrc file in your project root so the whole team uses the same version:

# Create .nvmrc file
echo "20" > .nvmrc

# Team members just run:
nvm use
# or
fnm use

CI/CD Issues: Docker Builds and GitHub Actions

npm install behaves differently in CI environments. Caching, permissions, and network settings all need special attention.

Docker Builds

Common mistakes in Dockerfiles:

# BAD Dockerfile — no layer caching, uses npm install
FROM node:20-alpine
WORKDIR /app
COPY . .
RUN npm install
CMD ["node", "index.js"]

# GOOD Dockerfile — proper layer caching, uses npm ci
FROM node:20-alpine
WORKDIR /app

# Copy package files first (layer caching!)
COPY package.json package-lock.json ./

# Use npm ci for deterministic installs
RUN npm ci --ignore-scripts

# Then copy the rest of the source
COPY . .

# Run any build steps after copy
RUN npm run build

CMD ["node", "index.js"]

Key points: copy package files first for layer caching, use npm ci instead of npm install in CI (it is faster and deterministic), and use --ignore-scripts if you do not need postinstall scripts.

GitHub Actions Caching

Proper caching can cut install time by 70%+:

# .github/workflows/ci.yml
name: CI
on: [push, pull_request]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'npm'  # Caches ~/.npm automatically

      - run: npm ci       # Deterministic install
      - run: npm test
      - run: npm run build

Decision Flowchart: npm install Failed — Follow This

Use this flowchart to diagnose your npm install failure:

1. Is it a permission error (EACCES / EPERM)?

YES -> Use nvm or fix directory ownership.

2. Is it a dependency conflict (ERESOLVE)?

YES -> Try --legacy-peer-deps first, then check version pinning.

3. Is it a network error (SOCKET_TIMEOUT / FETCH)?

YES -> Check proxy, VPN, or switch registry to npmmirror.com.

4. Is it a build/compilation error (node-gyp / code 1)?

YES -> Install build tools (python3, make, g++ / Visual Studio Build Tools).

5. Is it "Cannot find module" or strange behavior?

YES -> Delete node_modules + package-lock.json, then npm install.

6. Still failing?

YES -> Clean npm cache (npm cache clean --force), check Node version, try fresh clone.

Frequently Asked Questions

How do I fix "npm ERR! EACCES: permission denied" on Mac?

The best fix is to install Node.js through nvm (Node Version Manager) which installs to your home directory and avoids permission issues entirely. Run: curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash, then nvm install --lts. Alternatively, change the npm global directory: mkdir ~/.npm-global && npm config set prefix ~/.npm-global and add it to your PATH.

What does "npm ERR! ERESOLVE could not resolve" mean?

ERESOLVE means two or more packages in your dependency tree require different, incompatible versions of the same peer dependency. Starting with npm 7, this is a hard error. You can fix it by adding --legacy-peer-deps to your npm install command, which tells npm to ignore peer dependency conflicts (like npm 6 behavior), or by manually pinning compatible versions in your package.json overrides field.

Should I delete package-lock.json to fix npm install errors?

Deleting package-lock.json should be a last resort, not a first step. The lock file ensures deterministic installs. First try deleting only node_modules and running npm install. If that fails, then delete both node_modules and package-lock.json. Always commit the regenerated lock file.

Why does npm install fail in Docker but work locally?

Common causes: running as root without --unsafe-perm, missing native build tools (python3, make, g++) in the Docker image, COPY order preventing layer caching, or .dockerignore not excluding node_modules. Use npm ci instead of npm install in Docker for deterministic builds.

How do I fix "npm ERR! code 1" during npm install?

Error code 1 usually means a postinstall script failed, often a native module compilation (node-gyp). On macOS, install Xcode Command Line Tools: xcode-select --install. On Ubuntu/Debian: sudo apt install build-essential python3. On Windows: npm install -g windows-build-tools or install Visual Studio Build Tools.

What is the difference between npm install and npm ci?

npm install reads package.json and may update package-lock.json. npm ci (clean install) deletes node_modules, reads only package-lock.json, and installs exact versions. Use npm ci in CI/CD pipelines and Docker builds for faster, reproducible installs. Use npm install during local development when you need to update dependencies.

𝕏 Twitterin LinkedIn
บทความนี้มีประโยชน์ไหม?

อัปเดตข่าวสาร

รับเคล็ดลับการพัฒนาและเครื่องมือใหม่ทุกสัปดาห์

ไม่มีสแปม ยกเลิกได้ตลอดเวลา

ลองเครื่องมือที่เกี่ยวข้อง

{ }JSON FormatterYMLYAML Validator & Formatter.gi.gitignore Generator

บทความที่เกี่ยวข้อง

npm vs yarn vs pnpm vs bun: ใช้ Package Manager ไหนดีในปี 2026?

เปรียบเทียบ npm, yarn, pnpm และ bun ด้วย benchmark จริง

คู่มือ .env: แนวทางปฏิบัติที่ดีที่สุดสำหรับ Environment Variables

เชี่ยวชาญไฟล์ .env และ environment variables