捕获从NodeJS Lambda生成的进程的输出 [英] Capturing output from process spawned from NodeJS Lambda
问题描述
我正在尝试从使用NodeJS编写的AWS Lambda启动的外部程序中捕获输出.下面是完整的示例代码.任何测试事件都可以使用,因为它并未真正使用.
I'm trying to capture the output from an external program launched from an AWS Lambda written in NodeJS. Full example code below. Any test event would do since it's not really used.
exports.handler = async (event) => {
console.log ("Entering lambda" + JSON.stringify(event))
var spawn = require('child_process').spawnSync;
child_process = spawn ('aws', [' --version'], {
stdio: 'inherit',
stderr: 'inherit',
shell: true
})
console.log ("done");
const response = {
statusCode: 200,
body: JSON.stringify('done'),
};
return response;
};
运行它时,我得到以下输出(为简洁起见,我删除了测试事件详细信息,因为这无关紧要).
When I run it, I get the following as output (I removed the test event details for brevity, since it's irrelevant).
我看不到看到的是我期望的 aws --version
命令的结果(我正在使用它来测试AWS的正确调用CLI,但是任何Linux命令都可以).代码是同步执行,因为如果我将调用替换为 child_process = spawn('sleep',['1'],{
,lambda的执行时间将增加到1117.85 ms,因此发生了一秒钟的睡眠.但是执行日志中没有捕获任何内容.
What I don't see is the results of the aws --version
command that I expected (I'm using it to test the correct invocation of the AWS CLI, but any Linux command would do). The code does execute synchronously because if I replace the invocation with child_process = spawn ('sleep', ['1'], {
, lambda's execution time grows to 1117.85 ms, so the one-second sleep happens. But there's nothing captured in the execution logs.
START RequestId: 0c1287e2-d2ee-4436-a577-bc8ec3608120 Version: $LATEST
2019-01-16T19:12:45.130Z 0c1287e2-d2ee-4436-a577-bc8ec3608120 Entering lambda {...}
2019-01-16T19:12:45.143Z 0c1287e2-d2ee-4436-a577-bc8ec3608120 done
END RequestId: 0c1287e2-d2ee-4436-a577-bc8ec3608120
REPORT RequestId: 0c1287e2-d2ee-4436-a577-bc8ec3608120 Duration: 13.29 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 20 MB
我做错什么了吗?还是有其他方法可以捕获用NodeJS编写的Lambda的输出(状态代码,stdio,stderr)?
Am I doing something wrong? Or is there any other way to capture the output (status code, stdio, stderr) for a Lambda written in NodeJS?
推荐答案
这对我有用(node.js 8.10运行时)
This works for me (node.js 8.10 runtime)
exports.handler = async (event) => {
const spawnSync = require('child_process').spawnSync;
const process = spawnSync('echo', ['hello', 'world'], {
stdio: 'pipe',
stderr: 'pipe'
});
console.log(process.status);
console.log(process.stdout.toString());
};
尝试与 aws
一起运行时,会引发 ENOENT
错误.换句话说,该命令不可用.如@jarmod的问题注释中所述,我还认为Lambda容器中没有 awscli
.
When trying to run with aws
, it throws a ENOENT
error. In other words, the command is not available. As mentioned in the question comments by @jarmod, I also believe the awscli
is not available in the Lambda container.
可用的是SDK,因此您可以 require('aws-sdk');
而不将其捆绑到Lambda部署包中.
What is available is the SDK, so that you can require('aws-sdk');
without bundling it to your Lambda deployment package.
这篇关于捕获从NodeJS Lambda生成的进程的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!