Friday, 16 November 2018

Node can't find certain modules after synchronous install

I've got a script that synchronously installs packages at startup that looks like this

const cp = require('child_process')

;(function () {
  const r = require
  require = function (module) {
    try {
      console.log(`Requiring "${module}"`)
      return r(module)
    } catch (e) {
      console.log(`Module "${module}" not found.\nInstalling...`)
      cp.execSync(`npm install ${module}`)
      return r(module)
    }
  }
})()

const http    = require('http')
const express = require('express')
const fp      = require('find-free-port')
const io      = require('socket.io')
const md5     = require('js-md5')

When I uninstall a bunch of modules, they get installed successfully when I start the server again, which is what I want. However, the script starts throwing Cannot find module errors when I uninstall the first or second module of the list (not including child_process).

In this example, the error will be thrown when I uninstall express, unless I move its require to the bottom of the list ¯\_(• _ •)_/¯

Does anybody know what could be causing this?



from Node can't find certain modules after synchronous install

No comments:

Post a Comment