Last active
December 21, 2023 08:39
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
Dependencies: