-1

In our project we have the custom console object which is used as a logger.
So we need to replace the default console.
For this purpose we decided to use the vm module.
But we are facing the problem while using imports inside the code created with vm.Script:

application.js:

import path from 'path';

console.log(path.resolve('./apps'));

main.js:

const context = {
  console,
  global: {},
  module: {},
  exports: {},
  require,
};
context.global = global;

const sandbox = vm.createContext(context);
const fileName = './application.js';
const src = await fsp.readFile(fileName, 'utf8');
const script = new vm.Script(`module.exports = () => {\n${src}\n};`);
const execute = script.runInNewContext(sandbox);

execute();

Output:
Error: Cannot find module 'path'

Question:
How to make imports work properly inside the application.js file?

pospolitaki
  • 313
  • 2
  • 9
  • Uh, don't use `module.exports = () => {\n${src}\n};` ? An `import` declaration is obviously invalid inside a function. – Bergi May 04 '22 at 07:09

1 Answers1

1

Do not use a new vm.Script if you want to create a module. Use a new vm.Module instead! Notice that the API is still experimental though.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • would you mind to help with vm.Module in new [question](https://stackoverflow.com/questions/72130595/how-to-link-the-imported-dependencies-of-module-created-by-vm-sourcetextmodule-t)? – pospolitaki May 05 '22 at 16:30
  • The error "TypeError: Module is not a constructor" happens when changing to vm.Module – Jeferson Tenorio Feb 20 '23 at 09:47
  • @JefersonTenorio Looks like it's [`new vm.SourceTextModule`](https://nodejs.org/api/vm.html#class-vmsourcetextmodule) now and the `Module` class is abstract. Well, the API is marked as experimental still… – Bergi Feb 20 '23 at 09:51