node.js - AWS Lambda - NodeJS POST 请求和异步写入/读取文件

标签 node.js amazon-web-services asynchronous http-post aws-lambda

我是 NodeJS 的新手,在 AWS Lambda 内部,我正在尝试发出一个 POST 请求,该请求使用 JSON 对象调用外部 API,创建一个包含响应的文档,然后读取文件的内容。

来自 Ruby 背景,我认为问题源于我对异步编程的不熟悉,但我尝试使用回调和 readfileSync 只是为了调试但没有运气。

如有任何帮助,我们将不胜感激。

var querystring = require('querystring');
var https = require('https');
var fs = require('fs');

exports.handler = function(event, context) {
  console.log('Received event:', JSON.stringify(event, null, 2));

  var operation = event.operation;
  delete event.operation;

  var accessKey = event.accessKey;
  delete event.accessKey;

  var templateName = event.templateName;
  delete event.templateName;

  var outputName = event.outputName;
  delete event.outputName;

  var req = {
    "accessKey": accessKey,
    "templateName": templateName,
    "outputName": outputName,
    "data": event.data
  };

  function doPost(data, callback) {
    // Build the post string from an object
    var post_data = JSON.stringify(data);

    // An object of options to indicate where to post to
    var post_options = {
        host: 'hostname.com',
        port: '443',
        path: '/path/to/api',
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': post_data.length
        }
    };

    // Set up the request
    var file = fs.createWriteStream(outputName);

    var post_req = https.request(post_options, function(res) {
        res.setEncoding('utf8');
        res.pipe(file);

        res.on('response', function(response)  {
            console.log(response); 
        });

        res.on('error', function(e) {
            context.fail('error:' + e.message);
        })

        res.on('end', function() {
            context.succeed('success, end request listener');
        });
    });

    // post the data
    post_req.write(post_data);
    post_req.end();
    callback();
  }

  function printFileContents() {
    fs.readFileSync(outputName, 'utf8', function (err, data) {
        console.log('file contents:' + data);
    });            
  }

  switch (operation) {
    case 'create':
        // Make sure there's data before we post it
        if(req) {
            doPost(req, printFileContents);
            printFileContents();
        }
        break;
     ...
  }
};

最佳答案

一般来说,我建议这样开始:

var querystring = require('querystring');
var https = require('https');
var fs = require('fs');

exports.handler = function(event, context) {
    console.info('Received event', event);

    var data = {
        "accessKey": accessKey,
        "templateName": templateName,
        "outputName": outputName,
        "data": event.data
    };

    // Build the post string from an object
    var post_data = JSON.stringify(data);

    // An object of options to indicate where to post to
    var post_options = {
        host: 'hostname.com',
        port: '443',
        path: '/path/to/api',
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': post_data.length
        }
    };

    var post_request = https.request(post_options, function(res) {
        var body = '';

        res.on('data', function(chunk)  {
            body += chunk;
        });

        res.on('end', function() {
            context.done(body);
        });

        res.on('error', function(e) {
            context.fail('error:' + e.message);
        });
    });

    // post the data
    post_request.write(post_data);
    post_request.end();
};

您可以看到我大大简化了您的代码。我建议避免使用文件系统,因为那会减慢你的程序。我也不确定您函数的真正目标是什么,所以我只返回 HTTP 响应。

关于node.js - AWS Lambda - NodeJS POST 请求和异步写入/读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32636956/

相关文章:

Node.js - Gunzip 已读取的文件异步问题

javascript - 异步 forEach 函数返回未定义

jquery - 如何在 Node Express Web 服务器中使用 requirejs、jquery 和 d3

javascript - nodejs lstat 找不到文件

amazon-web-services - AWS Cognito 从用户池中删除所有用户

postgresql - 如何登录托管在 AWS RDS 上的 postgresql 服务器?

amazon-web-services - 来自 AWS API Gateway 的预检响应中的 Access-Control-Allow-Methods 不允许方法 PUT

javascript - 为什么带有 'await'的这行代码会触发微任务队列处理呢?

ruby-on-rails - 是否可以在 Rails 6 中禁用 Sass?

javascript - 如何将 Node.js 变量传递到 Pug 脚本标记的内部?