Выполните двоичный код командной строки с помощью Node.js
Я переношу библиотеку CLI с Ruby на Node.js. В моем коде я исполняю несколько сторонних двоичных файлов, когда это необходимо. Я не уверен, как лучше всего это сделать в Node.
Вот пример в Ruby, где я вызываю PrinceXML для преобразования файла в PDF:
cmd = system("prince -v builds/pdf/book.html -o builds/pdf/book.pdf")
Что такое эквивалентный код в Node?
Ответы
Ответ 1
Для еще более новой версии Node.js(v8.1.4) события и вызовы аналогичны или идентичны старым версиям, но рекомендуется использовать стандартные новые языковые функции. Примеры:
Для буферизованного вывода в формате, child_process.exec
потока (вы получаете все сразу), используйте child_process.exec
:
const { exec } = require('child_process');
exec('cat *.js bad_file | wc -l', (err, stdout, stderr) => {
if (err) {
// node couldn't execute the command
return;
}
// the *entire* stdout and stderr (buffered)
console.log('stdout: ${stdout}');
console.log('stderr: ${stderr}');
});
Вы также можете использовать его с Обещаниями:
const util = require('util');
const exec = util.promisify(require('child_process').exec);
async function ls() {
const { stdout, stderr } = await exec('ls');
console.log('stdout:', stdout);
console.log('stderr:', stderr);
}
ls();
Если вы хотите получать данные постепенно порциями (выводить в виде потока), используйте child_process.spawn
:
const { spawn } = require('child_process');
const child = spawn('ls', ['-lh', '/usr']);
// use child.stdout.setEncoding('utf8'); if you want text chunks
child.stdout.on('data', (chunk) => {
// data from standard output is here as buffers
});
// since these are streams, you can pipe them elsewhere
child.stderr.pipe(dest);
child.on('close', (code) => {
console.log('child process exited with code ${code}');
});
Обе эти функции имеют синхронный аналог. Пример для child_process.execSync
:
const { execSync } = require('child_process');
// stderr is sent to stderr of parent process
// you can set options.stdio if you want it to go elsewhere
let stdout = execSync('ls');
Так же как child_process.spawnSync
:
const { spawnSync} = require('child_process');
const child = spawnSync('ls', ['-lh', '/usr']);
console.log('error', child.error);
console.log('stdout ', child.stdout);
console.log('stderr ', child.stderr);
Примечание. Следующий код по-прежнему функционален, но в первую очередь предназначен для пользователей ES5 и более ранних версий.
Модуль для порождения дочерних процессов с Node.js хорошо документирован в документации (v5.0.0). Чтобы выполнить команду и извлечь ее полный вывод в виде буфера, используйте child_process.exec
:
var exec = require('child_process').exec;
var cmd = 'prince -v builds/pdf/book.html -o builds/pdf/book.pdf';
exec(cmd, function(error, stdout, stderr) {
// command output is in stdout
});
Если вам нужно использовать процессный ввод-вывод с потоками, например, когда вы ожидаете больших объемов вывода, используйте child_process.spawn
:
var spawn = require('child_process').spawn;
var child = spawn('prince', [
'-v', 'builds/pdf/book.html',
'-o', 'builds/pdf/book.pdf'
]);
child.stdout.on('data', function(chunk) {
// output will be here in chunks
});
// or if you want to send output elsewhere
child.stdout.pipe(dest);
Если вы выполняете файл, а не команду, вы можете использовать child_process.execFile
, параметры которого практически идентичны spawn
, но имеют четвертый параметр обратного вызова, такой как exec
для получения выходных буферов. Это может выглядеть примерно так:
var execFile = require('child_process').execFile;
execFile(file, args, options, function(error, stdout, stderr) {
// command output is in stdout
});
Начиная с v0.11.12, Node теперь поддерживает синхронный spawn
и exec
. Все методы, описанные выше, являются асинхронными и имеют синхронный аналог. Документацию для них можно найти здесь. Хотя они полезны для сценариев, обратите внимание, что в отличие от методов, используемых для асинхронного порождения дочерних процессов, синхронные методы не возвращают экземпляр ChildProcess
.
Ответ 2
Узел JS v12.9.1
, LTS v10.16.3
и v8.16.1
--- август 2019 г.
Асинхронный метод (Unix):
'use strict';
const { spawn } = require( 'child_process' );
const ls = spawn( 'ls', [ '-lh', '/usr' ] );
ls.stdout.on( 'data', data => {
console.log( 'stdout: ${data}' );
} );
ls.stderr.on( 'data', data => {
console.log( 'stderr: ${data}' );
} );
ls.on( 'close', code => {
console.log( 'child process exited with code ${code}' );
} );
Асинхронный метод (Windows):
'use strict';
const { spawn } = require( 'child_process' );
const dir = spawn( 'dir', [ '.' ] );
dir.stdout.on( 'data', data => console.log( 'stdout: ${data}' ) );
dir.stderr.on( 'data', data => console.log( 'stderr: ${data}' ) );
dir.on( 'close', code => console.log( 'child process exited with code ${code}' ) );
Синхронизация:
'use strict';
const { spawnSync } = require( 'child_process' );
const ls = spawnSync( 'ls', [ '-lh', '/usr' ] );
console.log( 'stderr: ${ls.stderr.toString()}' );
console.log( 'stdout: ${ls.stdout.toString()}' );
Из документации Node.js v12.9.1
То же самое касается документации Node.js v10.16.3 и документации Node.js v8.16.1
Ответ 3
Вы ищете child_process.exec
Вот пример:
const exec = require('child_process').exec;
const child = exec('cat *.js bad_file | wc -l',
(error, stdout, stderr) => {
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
if (error !== null) {
console.log(`exec error: ${error}`);
}
});
Ответ 4
const exec = require("child_process").exec
exec("ls", (error, stdout, stderr) => {
//do whatever here
})
Ответ 5
Начиная с версии 4, ближайшим вариантом является метод child_process.execSync
:
const {execSync} = require('child_process');
let output = execSync('prince -v builds/pdf/book.html -o builds/pdf/book.pdf');
Обратите внимание, что этот метод блокирует цикл обработки событий.
Ответ 6
Если вы хотите что-то похожее на верхний ответ, но также синхронный, то это будет работать.
var execSync = require('child_process').execSync;
var cmd = "echo 'hello world'";
var options = {
encoding: 'utf8'
};
console.log(execSync(cmd, options));
Ответ 7
Я просто написал помощника Cli, чтобы легко справляться с Unix/windows.
JavaScript:
define(["require", "exports"], function (require, exports) {
/**
* Helper to use the Command Line Interface (CLI) easily with both Windows and Unix environments.
* Requires underscore or lodash as global through "_".
*/
var Cli = (function () {
function Cli() {}
/**
* Execute a CLI command.
* Manage Windows and Unix environment and try to execute the command on both env if fails.
* Order: Windows -> Unix.
*
* @param command Command to execute. ('grunt')
* @param args Args of the command. ('watch')
* @param callback Success.
* @param callbackErrorWindows Failure on Windows env.
* @param callbackErrorUnix Failure on Unix env.
*/
Cli.execute = function (command, args, callback, callbackErrorWindows, callbackErrorUnix) {
if (typeof args === "undefined") {
args = [];
}
Cli.windows(command, args, callback, function () {
callbackErrorWindows();
try {
Cli.unix(command, args, callback, callbackErrorUnix);
} catch (e) {
console.log('------------- Failed to perform the command: "' + command + '" on all environments. -------------');
}
});
};
/**
* Execute a command on Windows environment.
*
* @param command Command to execute. ('grunt')
* @param args Args of the command. ('watch')
* @param callback Success callback.
* @param callbackError Failure callback.
*/
Cli.windows = function (command, args, callback, callbackError) {
if (typeof args === "undefined") {
args = [];
}
try {
Cli._execute(process.env.comspec, _.union(['/c', command], args));
callback(command, args, 'Windows');
} catch (e) {
callbackError(command, args, 'Windows');
}
};
/**
* Execute a command on Unix environment.
*
* @param command Command to execute. ('grunt')
* @param args Args of the command. ('watch')
* @param callback Success callback.
* @param callbackError Failure callback.
*/
Cli.unix = function (command, args, callback, callbackError) {
if (typeof args === "undefined") {
args = [];
}
try {
Cli._execute(command, args);
callback(command, args, 'Unix');
} catch (e) {
callbackError(command, args, 'Unix');
}
};
/**
* Execute a command no matters what the environment.
*
* @param command Command to execute. ('grunt')
* @param args Args of the command. ('watch')
* @private
*/
Cli._execute = function (command, args) {
var spawn = require('child_process').spawn;
var childProcess = spawn(command, args);
childProcess.stdout.on("data", function (data) {
console.log(data.toString());
});
childProcess.stderr.on("data", function (data) {
console.error(data.toString());
});
};
return Cli;
})();
exports.Cli = Cli;
});
Typescript исходный исходный файл:
/**
* Helper to use the Command Line Interface (CLI) easily with both Windows and Unix environments.
* Requires underscore or lodash as global through "_".
*/
export class Cli {
/**
* Execute a CLI command.
* Manage Windows and Unix environment and try to execute the command on both env if fails.
* Order: Windows -> Unix.
*
* @param command Command to execute. ('grunt')
* @param args Args of the command. ('watch')
* @param callback Success.
* @param callbackErrorWindows Failure on Windows env.
* @param callbackErrorUnix Failure on Unix env.
*/
public static execute(command: string, args: string[] = [], callback ? : any, callbackErrorWindows ? : any, callbackErrorUnix ? : any) {
Cli.windows(command, args, callback, function () {
callbackErrorWindows();
try {
Cli.unix(command, args, callback, callbackErrorUnix);
} catch (e) {
console.log('------------- Failed to perform the command: "' + command + '" on all environments. -------------');
}
});
}
/**
* Execute a command on Windows environment.
*
* @param command Command to execute. ('grunt')
* @param args Args of the command. ('watch')
* @param callback Success callback.
* @param callbackError Failure callback.
*/
public static windows(command: string, args: string[] = [], callback ? : any, callbackError ? : any) {
try {
Cli._execute(process.env.comspec, _.union(['/c', command], args));
callback(command, args, 'Windows');
} catch (e) {
callbackError(command, args, 'Windows');
}
}
/**
* Execute a command on Unix environment.
*
* @param command Command to execute. ('grunt')
* @param args Args of the command. ('watch')
* @param callback Success callback.
* @param callbackError Failure callback.
*/
public static unix(command: string, args: string[] = [], callback ? : any, callbackError ? : any) {
try {
Cli._execute(command, args);
callback(command, args, 'Unix');
} catch (e) {
callbackError(command, args, 'Unix');
}
}
/**
* Execute a command no matters what the environment.
*
* @param command Command to execute. ('grunt')
* @param args Args of the command. ('watch')
* @private
*/
private static _execute(command, args) {
var spawn = require('child_process').spawn;
var childProcess = spawn(command, args);
childProcess.stdout.on("data", function (data) {
console.log(data.toString());
});
childProcess.stderr.on("data", function (data) {
console.error(data.toString());
});
}
}
Example of use:
Cli.execute(Grunt._command, args, function (command, args, env) {
console.log('Grunt has been automatically executed. (' + env + ')');
}, function (command, args, env) {
console.error('------------- Windows "' + command + '" command failed, trying Unix... ---------------');
}, function (command, args, env) {
console.error('------------- Unix "' + command + '" command failed too. ---------------');
});
Ответ 8
Если вы не возражаете против зависимости и хотите использовать обещания, child-process-promise
работает:
монтаж
npm install child-process-promise --save
Использование exec
var exec = require('child-process-promise').exec;
exec('echo hello')
.then(function (result) {
var stdout = result.stdout;
var stderr = result.stderr;
console.log('stdout: ', stdout);
console.log('stderr: ', stderr);
})
.catch(function (err) {
console.error('ERROR: ', err);
});
использование икры
var spawn = require('child-process-promise').spawn;
var promise = spawn('echo', ['hello']);
var childProcess = promise.childProcess;
console.log('[spawn] childProcess.pid: ', childProcess.pid);
childProcess.stdout.on('data', function (data) {
console.log('[spawn] stdout: ', data.toString());
});
childProcess.stderr.on('data', function (data) {
console.log('[spawn] stderr: ', data.toString());
});
promise.then(function () {
console.log('[spawn] done!');
})
.catch(function (err) {
console.error('[spawn] ERROR: ', err);
});
Ответ 9
Теперь вы можете использовать shelljs (из узла v4) следующим образом:
var shell = require('shelljs');
shell.echo('hello world');
shell.exec('node --version')
Ответ 10
Ответ на @hexacyanide почти полный.
В команде Windows prince
может быть prince.exe
, prince.cmd
, prince.bat
или просто prince
(я не знаю, как связаны драгоценные камни, но урны npm поставляются с sh script и пакетом script - npm
и npm.cmd
).
Если вы хотите написать переносимый script, который будет работать в Unix и Windows, вы должны создать правильный исполняемый файл.
Вот простая, но портативная функция появления:
function spawn(cmd, args, opt) {
var isWindows = /win/.test(process.platform);
if ( isWindows ) {
if ( !args ) args = [];
args.unshift(cmd);
args.unshift('/c');
cmd = process.env.comspec;
}
return child_process.spawn(cmd, args, opt);
}
var cmd = spawn("prince", ["-v", "builds/pdf/book.html", "-o", "builds/pdf/book.pdf"])
// Use these props to get execution results:
// cmd.stdin;
// cmd.stdout;
// cmd.stderr;
Ответ 11
У меня была та же проблема, и я нашел ее навсегда. Это CLI, которую вы можете установить с помощью npm, и он отлично работал с моим малиновым пи! И если вы хотите запустить его при запуске, вы можете установить "forever-service". Они установят все, что вам нужно, чтобы поддерживать ваше приложение во все времена!
Посмотрите!
https://github.com/zapty/forever-service
https://www.npmjs.com/package/forever
Ответ 12
У меня есть похожая проблема, как насчет запуска двоичного файла в узле, который принимает почтовый запрос с данными в качестве входных данных и ответа на выход?
Ответ 13
Используйте этот легкий пакет npm
: system-commands
Посмотрите на это здесь.
Импортируйте это так:
const system = require('system-commands')
Запустите такие команды:
system('ls').then(output => {
console.log(output)
}).catch(error => {
console.error(error)
})