Skip to content

Instantly share code, notes, and snippets.

@mmckegg
Last active September 5, 2025 00:27
Show Gist options
  • Select an option

  • Save mmckegg/3467659a1faf2c44647e0c85d281fe61 to your computer and use it in GitHub Desktop.

Select an option

Save mmckegg/3467659a1faf2c44647e0c85d281fe61 to your computer and use it in GitHub Desktop.
Ensure that all dependencies match package-lock.json before starting ("cargo run" style)
// Ensure that all dependencies match package-lock.json before starting ("cargo run" style)
// add to package.json:
// scripts: {
// "prestart": "node scripts/ensure-deps.mjs"
// }
import { spawn } from "child_process"
const npmCmd = process.platform === "win32" ? "npm.cmd" : "npm"
function run(cmd, args, { quiet = false } = {}) {
return new Promise((resolve) => {
const p = spawn(cmd, args, {
cwd: process.cwd(),
env: {
...process.env,
npm_config_loglevel: quiet ? "error" : process.env.npm_config_loglevel,
},
stdio: quiet ? ["ignore", "pipe", "pipe"] : "inherit",
})
let out = ""
let err = ""
if (quiet) {
p.stdout.on("data", (d) => (out += d))
p.stderr.on("data", (d) => (err += d))
}
p.on("close", (code) => resolve({ code, out, err }))
})
}
function printProblems(jsonText, fallbackErr) {
try {
const j = JSON.parse(jsonText || "{}")
if (Array.isArray(j.problems) && j.problems.length) {
console.error(j.problems.join("\n"))
return
}
} catch {
//
}
if (fallbackErr && fallbackErr.trim()) {
console.error(fallbackErr.trim())
} else {
console.error("Dependency tree is inconsistent.")
}
}
let res = await run(npmCmd, ["ls", "--all", "--depth=Infinity", "--json"], { quiet: true })
if (res.code === 0) process.exit(0)
console.error("Dependencies not in sync with lockfile. Running npm install...")
printProblems(res.out, res.err)
const installArgs = ["install", "--no-audit", "--no-fund"]
const install = await run(npmCmd, installArgs, { quiet: false })
if (install.code !== 0) {
console.error("npm install failed.")
process.exit(install.code || 1)
}
res = await run(npmCmd, ["ls", "--all", "--depth=Infinity", "--json"], {
quiet: true,
})
if (res.code === 0) {
process.exit(0)
} else {
console.error("After npm install, dependencies are still inconsistent. Details:")
printProblems(res.out, res.err)
console.error("Try: npm ci (to reset node_modules), or resolve peer/dependency conflicts.")
process.exit(1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment