How to make the `import` statement work properly inside the code created using the node:vm module?

1k Views Asked by At

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?

1

There are 1 best solutions below

3
On BEST ANSWER

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.