【问题标题】:AWS Lambda - NodeJS POST request and asynch write/read fileAWS Lambda - NodeJS POST 请求和异步写入/读取文件
【发布时间】:2015-12-14 17:08:03
【问题描述】:

我是 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;
     ...
  }
};

【问题讨论】:

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


    【解决方案1】:

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

    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 响应。

    【讨论】:

    • var req 在这里根本没有被使用,并且 accessKey、templateName、outputName 没有在任何地方定义。这些是干什么用的?
    • 打错了,变量应该是data
    猜你喜欢
    • 2018-07-06
    • 1970-01-01
    • 2017-01-11
    • 2019-01-13
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    相关资源
    最近更新 更多