Possible to install all missing modules for a node application?

后端 未结 5 520
南旧
南旧 2021-01-30 21:13

I have a node app that I just started working with and each time I try to run it, it says there is a missing module. I\'ve just been using npm install ... for each

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-30 21:34

    I was inspired by @Aminadav Glickshtein's answer to create a script of my own that would synchronously install the needed modules, because his answer lacks these capabilities.

    I needed some help, so I started an SO question here. You can read about how this script works there.
    The result is as follows:

    const cp = require('child_process')
    
    const req = async module => {
      try {
        require.resolve(module)
      } catch (e) {
        console.log(`Could not resolve "${module}"\nInstalling`)
        cp.execSync(`npm install ${module}`)
        await setImmediate(() => {})
        console.log(`"${module}" has been installed`)
      }
      console.log(`Requiring "${module}"`)
      try {
        return require(module)
      } catch (e) {
        console.log(`Could not include "${module}". Restart the script`)
        process.exit(1)
      }
    }
    
    const main = async () => {
      const http    = await req('http')
      const path    = await req('path')
      const fs      = await req('fs')
      const express = await req('express')
    
      // The rest of the app's code goes here
    }
    
    main()
    

    And a one-liner (139 characters!). It doesn't globally define child_modules, has no last try-catch and doesn't log anything in the console:

    const req=async m=>{let r=require;try{r.resolve(m)}catch(e){r('child_process').execSync('npm i '+m);await setImmediate(()=>{})}return r(m)}
    
    const main = async () => {
      const http    = await req('http')
      const path    = await req('path')
      const fs      = await req('fs')
      const express = await req('express')
    
      // The rest of the app's code goes here
    }
    
    main()
    

提交回复
热议问题