如何从另一个JS文件中运行JS文件?

huangapple go评论67阅读模式
英文:

How do I run a JS file from another JS file?

问题

if (Bootup == "StartOS1") {
  // 在这里运行另一个JS文件的代码。
}
英文:

I am building a game inside the console, I'm using an NPM package called "prompts", and it asks from the user for the game, "What OS do you want to run?" and returns as JSON. For example if you selected "OS 1" it would return { Bootup: "StartOS1" }. What I want to do is basically to have an if statement like this:


if(Bootup == "StartOS1") {
 // The code to run another JS file here.
}

But I don't know what to put.

I've tried to do this with a NPM package called shelljs, which executes stuff in the shell:


const shell = require('shelljs')

if(Bootup == "StartOS1") {
  shell.exec('node OS1.js')
}

What this did was make my shell stuck on a blank line forever, and I had to restart it. This shows an example of what I'm trying to do.

答案1

得分: 0

shell.exec('node OS1.js')是一个同步函数,会阻塞你的程序。例如,如果你的JavaScript文件正在等待事件,它可能会无限期地阻塞你的函数。尝试使用child_processexec()方法,这应该会有所帮助:

const { exec } = require('child_process');

exec('node OS1.js', (e, stdout, stde) => {
  if (e) {
    console.error(`exec error: ${e}`);
    return;
  }
  console.log(`stdout: ${stdout}`);
  console.error(`stderr: ${stde}`);
});

还有一些其他方法可供使用,但这种方法将JavaScript文件作为字符串读取,然后通过另一个同步的eval函数执行它。尽管我听说这在安全性方面不是最佳实践。

const fs = require('fs');

fs.readFile('./node OS1.js', 'utf8', function(e, file) {
  if (e) {
    console.error(e);
    return;
  }
  eval(file);
});
英文:

shell.exec('node OS1.js') is a synchronous function that will block your program. For instance, if your js file is waiting on an event, it might block your functions indefinitely. Try child_process's exec() method. This should help:

const { exec } = require('child_process');

exec('node OS1.js', (e, stdout, stde) => {
  if (error) {
    console.error(`exec error: ${e}`);
    return;
  }
  console.log(`stdout: ${stdout}`);
  console.error(`stderr: ${stde}`);
});

There are also a couple of other methods you can use, but this one reads the js file as a string then executes it via the other synchronous eval function. Though I heard it's not the best practice when it comes to security.

const fs = require('fs');

fs.readFile('./node OS1.js', 'utf8', function(e, file) {
  if (e) {
    console.error(e);
    return;
  }
  eval(file);
});

huangapple
  • 本文由 发表于 2023年5月14日 09:57:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76245520.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定