Node can't find certain modules after synchronous install

后端 未结 3 1980
陌清茗
陌清茗 2021-01-07 11:23

I\'ve got a script that synchronously installs non-built-in modules at startup that looks like this

const cp = require(\'child_process\')

function requireOr         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-07 12:30

    cp.execSync is an async call so try check if the module is installed in it's call back function. I have tried it, installation is clean now:

    const cp = require('child_process')
    
    function requireOrInstall (module) {
        try {
            require.resolve(module)
        } catch (e) {
            console.log(`Could not resolve "${module}"\nInstalling`)
            cp.execSync(`npm install ${module}`, () => {
                console.log(`"${module}" has been installed`)
                try {
                    return require(module)
                } catch (e) {
                    console.log(require.cache)
                    console.log(e)
                }
            })
    
        }
        console.log(`Requiring "${module}"`)
    
    }
    
    const http    = require('http')
    const path    = require('path')
    const fs      = require('fs')
    const ffp     = requireOrInstall('find-free-port')
    const express = requireOrInstall('express')
    const socket  = requireOrInstall('socket.io')

    When node_modules not available yet :

    When node_modules available already:

提交回复
热议问题