Using nodejs child_process spawn

Asked 2 years ago, Updated 2 years ago, 86 views

I want to run the following code in nodejs.

$ gcc test.c
$ $ ./a.out < inputfile.txt

So I wrote the following code.

var gpp = spawn('g++', ['test.cpp']);
var run = spawn('./a.out', ['< input.txt']);
var run = spawn('./a.out < input.txt']);

The compilation went well, but in the execution section
I tried as above, but it didn't work.

What I want to do is to enter input.txt in a.out I'm asking you a question because it didn't go as I thought.

What should I do?

To ask you another question

I'm referring to the official document

child_process.spawn(command[, args][, options])

I want to know exactly what args should be put in here.

node.js spawn subprocess

2022-09-22 15:04

1 Answers

It's a self-answer.

I asked question on StackOverflow.

I received the following answer.

Since < (redirection) is a shell construct, you need to run your command line with a shell. That's what child_process.exec() is for:

const exec = require('child_process').exec;

exec('./a.out < inputfile.txt', function(err, stdout, stderr) {
  if (err) {
    return console.error('exec error:', err);
  }
  console.log('stdout:', stdout);
  console.log('stderr:', stderr);
});


2022-09-22 15:04

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.