Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

314
Visualizações
How to make the `import` statement work properly inside the code created using the node:vm module?

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda