Skip to content

Instantly share code, notes, and snippets.

@dctalbot
Last active December 21, 2023 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dctalbot/4465edc78a0a6f76f02e9c3be8d77f99 to your computer and use it in GitHub Desktop.
Save dctalbot/4465edc78a0a6f76f02e9c3be8d77f99 to your computer and use it in GitHub Desktop.
Node script to get a flat list of all npm dependencies in a project
// USAGE: npm ls --all --json | node deps.js > result.json
import * as fs from "fs";
import * as _ from "lodash-es";
import * as crypto from "crypto";
const VERSION_NONCE_DELIM = crypto.randomBytes(20).toString("hex");
const isObject = (val) => val && typeof val === "object" && !Array.isArray(val);
function listAllAttrs(obj, result = []) {
const addDelimiter = (a, b) => (a ? `${a}.${b}` : b);
const paths = (obj = {}, head = "") => {
return Object.entries(obj).reduce((agg, [key, value]) => {
let fullPath = addDelimiter(head, key);
let ver = key === "version" ? value : "";
return isObject(value)
? agg.concat(paths(value, fullPath))
: agg.concat(fullPath + (ver ? VERSION_NONCE_DELIM + ver : ""));
}, []);
};
return paths(obj);
}
function main() {
//read from stdin
const obj = JSON.parse(fs.readFileSync(0));
// represent as line items
const attrs = listAllAttrs(obj.dependencies);
const result = _.chain(attrs)
.filter((x) => x.includes(VERSION_NONCE_DELIM))
.map((x) => {
const [path, version] = x.split(VERSION_NONCE_DELIM);
const splat = path.split(".");
return splat[splat.length - 2] + "@" + String(version);
})
.uniq()
.sort()
.value();
console.log("%j", result);
}
main();
@dctalbot
Copy link
Author

dctalbot commented Dec 21, 2023

This is a node script that will read a dependency graph from stdin and write a flat list to stdout in JSON format.

Typical usage from a shell looks like:

npm ls --all --json | node list_npm_dependencies.js .js > result.json

Dependencies:

  • node v18.15.0
  • npm 9.5.0
  • lodash-es

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment