首页 > 解决方案 > 关于如何从另一个 nodejs 脚本调用无服务器 shell 命令的任何想法

问题描述

我正在尝试调用无服务器命令,例如

serverless invoke local -f hello

但来自另一个nodejs脚本。我使用节点 child_process spawn 对其进行测试

const {spawn} = require ('child_process');
const cmd = 'serverless invoke local -f hello';
const p = spawn (cmd, [], {shell: true});

p.stdout.on ('data', (data) => {
    console.log (data.toString ());
});

或使用 exec

const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function main() {
    const { stdout, stderr } = await exec('serverless invoke local -f hello');

    if (stderr) {
        console.error(`error: ${stderr}`);
    }
    console.log(`${stdout}`);
}

main()

当我从终端运行这两种解决方案时

节点 myscript.js

我无法得到任何回应,任何关于如何做到这一点的建议或想法都会非常有帮助

标签: node.jsserverless-frameworkserverless

解决方案


代码:

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

const child = spawnSync('serverless', ['invoke', 'local', '-f', 'hello'])

console.log(child.output.toString('utf8'))

回复:

,{
    "statusCode": 200,
    "body": "{\n  \"message\": \"Go Serverless v1.0! Your function executed successfully!\",\n  \"input\": \"\"\n}"
}
,

推荐阅读