вторник, 29 октября 2013 г.

How to automatically build the package.json file for Node.js projects?

Open command line tool (run cmd.exe).

Go to your project directory

cd C:\Work\MyProjectFolder

Excute command

npm init

to generate package.json file in your project directory.

Then use this simple script for Node JS to collect all dependencies for your project in ./node_modules folder:

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 this dependencies into your package.json file.

Комментариев нет:

Отправить комментарий