I am interested in redirecting command line output to a file rather than displaying it in the standard

Is it possible to use child-process and spawn in node.js to execute a command and save the output to a file instead of displaying it on the standard output?

test.js

const expect = require('chai').expect;
const { spawn } = require('child_process')
let path = require('path');
let fs = require('fs');

//I tried below code but it didn't work 
1) const cmd = spawn(ansysfnonetclient, options, {
    stdio: [
      0, // Use parent's stdin for child.
      'pipe', // Pipe child's stdout to parent.
      fs.openSync('err.out', 'w') // Direct child's stderr to a file.
    ]
});

2) const cmd = spawn(ansysfnonetclient, options, {shell: true, stdio: 'inherit'});


it('run the cmd and write o/p to file', function (done) {
  this.timeout(30000); 
 let options = ['-h','-o','temp.log'];

 let ansysfnonetclient = path.resolve(__dirname,'../../../../../../../../saoptest/annetclient.exe');

 const cmd = spawn(ansysfnonetclient, options, {shell: true, stdio: 'inherit'});
 console.log(cmd);
 done();

});

Answer №1

stdio feature allows passing 3 "files":

  • input
  • output
  • error output

To redirect regular output to a file, you need to specify the file as the second item in the stdio array:

const { spawn } = require('child_process');
const fs = require('fs');

const stdio = [
  0,
  fs.openSync('std.out', 'w'),
  fs.openSync('err.out', 'w')
];

const child = spawn('echo', ['hello world!'], {stdio});

For more information on this topic, visit: https://nodejs.org/api/child_process.html#child_process_options_stdio.

Answer №2

const expect = require('chai').expect;
const { spawn } = require('child_process');
let path = require('path');
let fs = require('fs');

const cmd = spawn(ansysfnonetclient, options,  {shell: true, stdio: 'inherit'});

cmd.stdout.on('data',function(chunk) {

fs.writeFile(path.resolve(__dirname,'../../../../../../../../output.log'), chunk.toString(), function(err) {

  if(err) 
  {
    return console.log(err);
  }

  console.log("The file was saved!");
}); 

Inspired by the discussion on Stack Overflow about capturing STDOUT in Node.js using child_process.spawn

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Effortless bug tracking in Chrome developer tools

When I'm debugging, I want the code to be displayed in Chrome browser (or another browser like Edge) exactly as it was written. Even when using pretty print, the code still appears unreadable. For example, a block of code written in my IDE: {provideD ...

Error: EPERM: unable to perform operation, remove 'C:wamp64wwwdev ode_modules.staging'

Can someone assist me with this npm error? NPM version: 5.5.1, Node version: 8.9.1, OS: Windows 10 64-bit S C:\wamp64\www\dev> npm install bulma npm ERR! path C:\wamp64\www\dev\node_modules\.staging npm ERR! ...

Exploring Tmbd Movie Database with React.js - Results of searches will only display after the application is recompiled

Presented here is my component. The challenge I am facing pertains to the fact that upon entering a search query, no results are displayed until I manually save in the code editor and trigger a recompilation of the application. Is there a more efficient ap ...

Discord between Bootstrap tabs and C3 charts: A Compatibility Str

On my website, I have implemented Bootstrap navigation tabs that each contain a chart. The issue I am facing is that when I navigate to the home page, the chart in the active tab displays perfectly fine. However, for the other tabs, the charts overlap with ...

Using $stateParams injection for unit testing Angular applications with Karma

Here is the starting point for the controller code: angular .module('hc.hotelContent') .controller('NameLocationController', nameLocationCtrlFn); //Todo change hotelDataService nameLocationCtrlFn.$inject = ['$stateParams', &a ...

JS animation triumphant

I have developed an app that utilizes a checkbox to control the appearance of an overlay on a screen. To ensure smooth transitions, I have incorporated animations into the process. #overlay{ position:absolute; height: 100vh; width: 100vw; ...

Node.js: Organizing multiple routes in a single router file

Is it possible to have multiple routes defined in a single router file? For example, let's say we have Company and User tabs and I want to have 1 router file for each tab. All company-related calls should be handled by the Company router and user-rela ...

Troubleshooting the sidebar pin-unpin problem using Jquery and CSS

I have created a single side panel that allows me to toggle between opening and closing the sidebar by hovering on it. I can also pin and unpin the sidebar by clicking on the pin image. Now, I want to open the sidebar onClick instead of onHover and remove ...

Error: Attempting to access the 'getProvider' property of an undefined variable

I am encountering an error that says "property of undefined (reading getProvider)" while deploying my function to Firebase. I am currently trying to figure out how to obtain the auth instance. When I attempt to use firebase.auth, it results in another er ...

Arranging elements in an array based on two different properties

Trying to organize an array of elements (orders details). https://i.stack.imgur.com/T2DQe.png [{"id":"myid","base":{"brands":["KI", "SA"],"country":"BG","status":&qu ...

How to send a JavaScript variable to Flask and trigger an AJAX reload action

Introduction: I have explored similar inquiries and attempted to apply relevant code/concepts but without success. -https://stackoverflow.com/questions/43645790/passing-javascript-variable-to-python-flask -https://stackoverflow.com/questions/10313001/is- ...

What is the best way to post an image using nodejs and express?

Recently, I've been working on a CMS for a food automation system and one feature I want to incorporate is the ability to upload pictures of different foods: <form method="post" enctype="multipart/form-data" action="/upload"> <td>< ...

Execute the getJSON calls in a loop for a count exceeding 100, and trigger another function once all

In order to process a large grid of data, I need to read it and then make a call to a $getJSON URL. This grid can contain over 100 lines of data. The $getJSON function returns a list of values separated by commas, which I add to an array. After the loop fi ...

Exploring the connections between PHP, JavaScript, JSON, and AJAX

While this question may lean more towards conceptual understanding rather than pure programming, it is essential for me to grasp how these mechanisms interact in order to code effectively. My current knowledge includes: 1) PHP as a programming language ...

The ajax code is failing to retrieve the data from the table and populate it in the

hi guys i have an issue on ajax. where ajax can't work to take the data of second rows. This's code in model function getdtbarang($barcode = FALSE) { if ($barcode === FALSE) { $query = $this->db1->get(&a ...

What is causing the Firebase emulator to crash when I run my Express code?

This project is utilizing express.js along with firebase. Whenever attempting to access a different file containing routes, it results in failure. Instead of successful emulation, an error is thrown when running this code: const functions = require(" ...

`npm security check reveals a potential vulnerability related to Inefficient Regular Expression Complexity. For more information, refer to: https://github.com/advisories/GHSA-9vvw-cc

# npm audit report debug <3.1.0 debug Inefficient Regular Expression Complexity vulnerability - https://github.com/advisories/GHSA-9vvw-cc9w-f27h No solution currently available node_modules/body-parser/node_modules/debug node_modules/express/node_modu ...

Selenium unable to interact with Javascript pop-up box

I am currently working on automating a feature for our web application, specifically a form of @mentioning similar to Facebook. On the front end, when a user types @ into a text input, the API is called to retrieve the list of users and display them in a b ...

Toggling forms with HTML <select> elements: A step-by-step guide

In the process of creating a web application, I am faced with the task of registering users based on their specific category. To accomplish this, I have incorporated a combo-box where users can indicate their user type. My objective is to display an appro ...

The styles order definition in the Material-UI production build may vary from that in development

When using material-ui, an issue arises in the production build where the generated styles differ from those in development. The order of the material-ui styles in production does not match the order in development. In DEV, the material-ui styles are defi ...