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
Patricia ArquetteOriginal
2024-12-25 09:20:11950browse

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
});

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
});

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');

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
});

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!

Statement:
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