Node js can I get the exit code from the windows command line app written in C++?

  • 9 months ago
Comment

ChatGPT
1 / 1

Yes, you can get the exit code from a Windows command-line application written in C++ when executing it from a Node.js script. The child_process module in Node.js allows you to spawn a child process and interact with it, including capturing the exit code.

Here's an example of how you can execute a C++ command-line application from a Node.js script and capture its exit code:

  1. Create a C++ Application:
    Write a simple C++ program that returns an exit code. For example, save the following code as myapp.cpp:
cpp
#include <iostream>

int main() {
std::cout << "Hello from C++" << std::endl;
return 42; // Return the exit code
}
  1. Compile the C++ Application:
    Compile the C++ program using a C++ compiler like g++:
bash
g++ -o myapp myapp.cpp
  1. Create a Node.js Script:
    Now create a Node.js script (app.js) to execute the compiled C++ application and capture its exit code:
javascript
const { spawnSync } = require('child_process');

const appPath = './myapp'; // Path to the compiled C++ application

const result = spawnSync(appPath);

if (result.error) {
console.error('Error:', result.error);
} else {
console.log('Exit Code:', result.status);
}
  1. Run the Node.js Script:
    Run the Node.js script using the following command:
bash
node app.js

The Node.js script will execute the compiled C++ application (myapp) and capture its exit code. The exit code will be available in the status property of the result object.

Remember to adjust file paths and names according to your setup. Also, ensure that you have the necessary permissions to execute the C++ application and run Node.js scripts.