Execute javascript code in nodejs using spawn

Question:

I wrote below code in node js to execute python code and print logs and return output using spawn,

const { spawn } = require('node:child_process');
const ls = spawn('node', ['-c', "python code content will come here"]);
ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

it works fine, but now i want to execute javascript code in the place of python code , can somebody have any idea how we can do it or my command is wrong.

Below is my code to execute javascript code

const { spawn } = require('node:child_process');

jscode = `var hello = function() {
  console.log("log from DB function!");
  console.log(`{"return":"Return from DB function!"}`);
};

hello(); 
`
const ls = spawn('node', ['-c', jscode]);

ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});
Asked By: pbhle

||

Answers:

You can use -e, --eval "script"(Equivalent to -c for Python) option which will evaluate the argument as JavaScript.

$ node --help | grep "-e,"
  -e, --eval=...              evaluate script

So your javascript code should looks like this.

# out.js
const { spawn } = require('node:child_process');

jscode = `var hello = function() {
  console.log("log from DB function!");
};

hello(); 
`
const ls = spawn('node', ['-e', jscode]);

ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

Running this function produces the following output.

$ node out.js
stdout: log from DB function!
Answered By: Abdul Niyas P M
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.