Is there a way to automatically build the package.json file for Node.js projects
The package.json file is used by npm to learn about your node.js project.
Use npm init
to generate package.json files for you!
It comes bundled with npm. Read its documentation here: https://docs.npmjs.com/cli/init
Also, there's an official tool you can use to generate this file programmatically: https://github.com/npm/init-package-json
npm init
to create the package.json file and then you use
ls node_modules/ | xargs npm install --save
to fill in the modules you have in the node_modules folder.
Edit: @paldepind pointed out that the second command is redundant because npm init
now automatically adds what you have in your node_modules/ folder. I don't know if this has always been the case, but now at least, it works without the second command.
I just wrote a simple script to collect the dependencies in ./node_modules. It fulfills my requirement at the moment. This may help some others, I post it here.
var fs = require("fs");
function main() {
fs.readdir("./node_modules", function (err, dirs) {
if (err) {
console.log(err);
return;
}
dirs.forEach(function(dir){
if (dir.indexOf(".") !== 0) {
var packageJsonFile = "./node_modules/" + dir + "/package.json";
if (fs.existsSync(packageJsonFile)) {
fs.readFile(packageJsonFile, function (err, data) {
if (err) {
console.log(err);
}
else {
var json = JSON.parse(data);
console.log('"'+json.name+'": "' + json.version + '",');
}
});
}
}
});
});
}
main();
In my case, the above script outputs:
"colors": "0.6.0-1",
"commander": "1.0.5",
"htmlparser": "1.7.6",
"optimist": "0.3.5",
"progress": "0.1.0",
"request": "2.11.4",
"soupselect": "0.2.0", // Remember: remove the comma character in the last line.
Now, you can copy&paste them. Have fun!
First off, run
npm init
...will ask you a few questions (read this first) about your project/package and then generate a package.json file for you.
Then, once you have a package.json file, use
npm install <pkg> --save
or
npm install <pkg> --save-dev
...to install a dependency and automatically append it to your package.json
's dependencies
list.
(Note: You may need to manually tweak the version ranges for your dependencies.)