简体   繁体   中英

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

searching on internet its look like using

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:

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:

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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