Is it possible to automatically install the required modules for a node.js script?

Yes, there is a great piece of code called NPM for exactly this: https://npmjs.org/

You specify dependent packages in a package.json file (see the docs for syntax) and you can use npm install . to pull them in all at once, and then require them from your script.

Package.json syntax page: https://docs.npmjs.com/getting-started/using-a-package.json

The first time you install a module, your can provide any number of modules to install, and add the --save argument to automatically add it to your package.json

npm i --save dnode request bluebird

The next time, someone will execute npm i it will automatically install all the modules specified in your package.json


I have written a script for this.
Place it at the start of your script, and any uninstalled modules will be installed when you run it.

(function () {
  var r = require
  require = function (n) {
    try {
      return r(n)
    } catch (e) {
      console.log(`Module "${n}" was not found and will be installed`)
      r('child_process').exec(`npm i ${n}`, function (err, body) {
        if (err) {
          console.log(`Module "${n}" could not be installed. Try again or install manually`)
          console.log(body)
          exit(1)
        } else {
          console.log(`Module "${n}" was installed. Will try to require again`)
          try{
            return r(n)
          } catch (e) {
            console.log(`Module "${n}" could not be required. Please restart the app`)
            console.log(e)
            exit(1)
          }
        }
      })
    }
  }
})()

Tags:

Node.Js