简体   繁体   English

如何在javascript代码中执行另一个nodejs?

[英]how to execute another nodejs inside javascript code?

how to execute another js code but using nodejs,, I mean how to do like this, node index2.js inside index.js ,what should I write inside index.js如何执行另一个js代码但使用nodejs,我的意思是如何做这样的,index.js里面的node index2.js,我应该在index.js里面写什么

searching on internet its look like using在互联网上搜索它看起来像使用

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

but I have no Idea my brain can't get it,但我不知道我的大脑无法理解,

pls someone give me some example if possible thanks如果可能的话,请有人给我一些例子谢谢

You can use child_process like so:您可以像这样使用child_process

const { exec } = require("child_process");
var index2 = exec("./index2.js");

instead of doing that, you're working two scripts with the same language.而不是这样做,您正在使用相同的语言处理两个脚本。 So, if you have a function or something you can simply import it doing:所以,如果你有一个函数或其他东西,你可以简单地导入它:

var index2 = require('./index2')

if you need to execute another script written in bash for example... you have to do this:例如,如果您需要执行另一个用 bash 编写的脚本……您必须这样做:

const { exec } = require('child_process');
exec('python example.py', (err, stdout, stderr) => {
  if (err) {
    // node couldn't execute the command
    return;
  }

  // the *entire* stdout and stderr (buffered)
  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);
});

Hope it helps!希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM