Home > Web Front-end > JS Tutorial > How Can I Execute Command Line Binaries and Files in Node.js?

How Can I Execute Command Line Binaries and Files in Node.js?

Patricia Arquette
Release: 2024-12-25 09:20:11
Original
915 people have browsed it

How Can I Execute Command Line Binaries and Files in Node.js?

Executing Command Line Binaries in Node.js

In Node.js, the process of executing command line binaries is handled through the child_process module. Whether you need to execute a command or handle process I/O with streams, there are options to meet your requirements.

Asynchronous Execution

Executing Commands with Buffers

To execute a command and fetch its complete output as a buffer, use child_process.exec():

const { exec } = require('child_process');

exec('command', (error, stdout, stderr) => {
  // command output is in stdout
});
Copy after login

Streaming Output

If you need to handle process I/O with streams, use child_process.spawn():

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

const child = spawn('command', ['args']);

child.stdout.on('data', (chunk) => {
  // output will be here in chunks
});
Copy after login

Synchronous Execution

Node.js also supports synchronous spawn and exec methods. These methods do not return an instance of ChildProcess:

const { execSync } = require('child_process');

let stdout = execSync('command');
Copy after login

Executing Files

In case you need to execute a file rather than a command, use child_process.execFile():

const { execFile } = require('child_process');

execFile('file', ['args'], (error, stdout, stderr) => {
  // command output is in stdout
});
Copy after login

The above is the detailed content of How Can I Execute Command Line Binaries and Files in Node.js?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template