赞
踩
shell脚本spawn
There are occasions when running a Python/Ruby/PHP shell script from Node.js is necessary. This post looks at best practices around leveraging child_process.spawn to encapsulate this call in Node.js/JavaScript.
有时需要从Node.js运行Python / Ruby / PHP Shell脚本。 这篇文章探讨了围绕child_process.spawn将此调用封装在Node.js / JavaScript中的最佳实践。
The goal here is to have an interoperability layer between Node.js and an outside shell. This is a quick workaround if some other part of your system isn’t developed in JavaScript.
这里的目标是在Node.js和外部外壳之间具有一个互操作性层。 如果系统的其他部分未使用JavaScript开发,则这是一种快速的解决方法。
We’ll use spawn
over exec
because we’re talking about passing data and potentially large amounts of it. To understand the difference between child_process.spawn
and child_process.exec
see “Difference between spawn and exec of Node.js child_process”.
我们将在exec
之上使用spawn
,因为我们正在谈论传递数据以及潜在的大量数据。 要了解child_process.spawn
和child_process.exec
之间的child_process.spawn
,请参阅“ Node.js child_process的spawn和exec之间的区别 ”。
The long and short of it is use exec
for small amounts of data (under 200k) using a Buffer interface and spawn
for larger amounts using a stream interface.
它的长处和spawn
是通过Buffer接口使用exec
来处理少量数据(200k以下),而使用stream接口使用exec
来产生大量数据。
spawn
has a more verbose syntax for some of the use-cases we’ll look at. It’s more serviceable for integrating with Ruby/Python/PHP since we might get more data than a couple of lines of text.
对于我们将要看到的一些用例, spawn
具有更详细的语法。 与Ruby / Python / PHP集成时,它更具服务性,因为我们可能会获得比两行文本更多的数据。
Full examples github.com/HugoDF/node-run-python.
完整示例github.com/HugoDF/node-run-python 。
The following examples contain 2 sections:
以下示例包含2个部分:
The part that actually runs the shell command, usually a function called run
, and
实际运行shell命令的部分,通常是一个称为run
的函数,以及
an IIFE (“immediately invoked function expression”) that actually calls it, (async () => { await run() }
)(). This IIFE is a nice pattern enabled by async/await (see Async JS: history, patterns and gotchas) but it’s just there for illustration purposes since it represents the call to the wrapped sp
awn call from another part of your application.
实际调用它的IIFE(“立即调用的函数表达式”), (async () => { await run() }
)()。 这IIFE是一个很好的模式能够通过异步/的await(S EE异步JS:历史,模式和gotc有),但它只是在那里用于说明目的,因为它代表了调用wrapp ed sp
从应用程序的其他部分芒电话。
Using spawn
is overkill in this situation since echo is only going to return what’s passed to it.
在这种情况下,使用spawn
会显得过大,因为echo只会返回传递给它的内容。
The example is pretty self-explanatory and shows how to use child_process.spawn
to “shell out” and read that data back.
该示例是不言自明的,并说明了如何使用child_process.spawn
进行“ shell out”并读回该数据。
spawn
takes the executable to call as the first parameter and optionally an array of options/parameters for the executable as the second parameter.
spawn
将可执行文件作为第一个参数,并将可选的选项/参数数组作为第二个参数。
- const { spawn } = require('child_process');
- function run() {
- const process = spawn('echo', ['foo']);
- process.stdout.on(
- 'data',
- (data)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。