NodeJS有“需要或下载”的简写方法吗?

时间:2017-04-09 20:27:25

标签: javascript node.js

我正在尝试创建能够智能地找到运行方式的代码,不会问任何问题,而不是抱怨缺少依赖项。我真正想要的是像

var aes256 = require_or_install('nodejs-aes256');

等于

var aes256 = null;
try {
  aes256 = require('nodejs-aes256');
} catch(e) {
  const exec = require('child_process').exec;
  console.log('nodejs-aes256 not found. I\'ll fix that for you.');
  exec('npm install --save nodejs-aes256');
  aes256 = require('nodejs-aes256');
}

1 个答案:

答案 0 :(得分:1)

What you could do is add all your dependencies to your package.json and add npm install to your start script, like this:

{
  "name": "project",
  (...),
  "main": "index.js",
  "scripts": {
    "start": "npm install && node index.js"
  },
  "dependencies": {
    "nodejs-aes256": "*"
  }
}

Then, to start your program, run:

npm start

Note that this is going to trigger npm and will increase your program start up by a few seconds. If its dependencies have already been installed, npm will not install them again.