Trying to build a Node CLI to do some backup tasks including fetching NPM packages. I ended up writing this function:
function getNPNGlobalPackages(cb) {
require('child_process').exec(
'npm list -g --json',
function (err, res, err) {
if (err) return cb(err);
const result = JSON.parse(res);
const packages = result.dependencies;
console.log(packages);
}
);
}
The issue with this result is I can't edit output and I feel there could be better approach to do it.
Output:
{
'@ionic/cli': { version: '6.18.0' },
'@nestjs/cli': { version: '8.1.5' },
'@vue/cli-init': { version: '4.5.13' },
'@vue/cli': { version: '4.5.13' },
...
}
When I try to get packages[0]
I get undefined
. What am I doing wrong ?
My goal is to end up having something like packagename@version
.
CodePudding user response:
packages is an object. So, if you want to get a value you have to get it by key (Here you are trying to get from index).
For your end goal try this
const res = Object.keys(packages).map(pkg => `${pkg}@${packages[pkg]['version']}`);