繁体   English   中英

将JSON文件加载到DynamoDB中

[英]Loading a json file into DynamoDB

当我使用本地文件与Node一起执行该JavaScript代码时,它的效果很好,但是现在当我在命令行中运行该脚本时,我得到“ Undefined:1”。

var AWS = require('aws-sdk');
const http = require("http");

AWS.config.update({ region: "us-east-1" });

//cron(0 18 ? * MON-FRI *)
var docClient = new AWS.DynamoDB.DocumentClient();

console.log("Importing Work Orders into DynamoDB Jobs table. Please wait.");

http.get('http://www.MyWebSite.com/Data/WOjson/02152018.json', (res) => {
  const { statusCode } = res;
  const contentType = res.headers['content-type'];

  let error;
  if (statusCode !== 200) {
    error = new Error('Request Failed.\n' +
                      `Status Code: ${statusCode}`);
  } else if (!/^application\/json/.test(contentType)) {
    error = new Error('Invalid content-type.\n' +
                      `Expected application/json but received ${contentType}`);
  }
  if (error) {
    console.error(error.message);
    // consume response data to free up memory
    res.resume();
    return;
  }

console.log("Now it is time to parse the file.");

  res.setEncoding('utf8');
  let rawData = '';

res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
  });
const parsedData = JSON.parse(rawData);

parsedData.forEach(function(job) {
    var params = {
        TableName: "Jobs",
        Item: {
            "userId":  job.userId,
            "WorkOrder": job.WorkOrder,
            "ServiceDate":  job.ServiceDate,
            "JobType": job.JobType
        }
    };

// Here is where I post to the DynamoDB table
    docClient.put(params, function(err, data) {
       if (err) {
           console.error("Unable to add job", job.WorkOrder, ". Error JSON:", JSON.stringify(err, null, 2));
       } else {
           console.log("PutItem succeeded:", job.WorkOrder);
       }
    });
});


}).on('error', (e) => {
  console.error(`Got error: ${e.message}`);
});

我已经更新了代码以使用http。 我确实收到了控制台日志消息,“现在是时候解析文件了。”,但随后却收到消息“ Undefined:1”,并且没有项目进入我的DynamoDB表中。

res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
  });
const parsedData = JSON.parse(rawData);

parsedData.forEach(function(job) {

理想情况下,我想按计划执行该lambda函数(每天一次,例如在晚上6点)以将远程文件读入我的DynamoDB表中。

我与fs API的合作不多,但是对于您的用例,我认为它并不理想,因为我认为它处理的是本地(相对于服务器)文件系统,而不是远程文件系统。 从理论上讲,AWS提供对/tmp文件夹的访问权限,我认为这是短暂的,因此我也不认为这是存储数据的好地方。 对于您的用例,我可以考虑两种处理相同方法的方法:

  1. 捆绑一个处理http请求的模块(例如请求模块),然后将其用于在Lambda上与远程文件进行交互时,从本质上讲,它将类似于:
if(process.env.USE_REMOTE_FS) {
  const request = require('request');
  // use request module
  // async/await or turn to a promise
  request.get('http://www.MyWebSite.com/Data/WOjson/02152018.json',...)
  ...
} else {
  const fs = require('fs');
  // use fs module
  ...
}
  1. 捆绑一个为您处理详细信息的模块。 在Ruby中,有一个open-uri Gem,我认为node open-uri存在一个类似的对象,它可以根据传入的uri做类似的事情。
const open = require('open-uri');
// you can async/await or turn this to a promise
open(uri, function(err, jsonData) { JSON.parse(jsonData) });

如果您不想处理过多的功能管理和部署,也可以使用低级http模块而不是request模块。

更新1

我只是检查了fs的文档,似乎readFileSync应该可以工作,但是您应该提供URL对象,因此从本质上讲 ,我想您会首先创建URL并将其传递给fs。 就个人而言,我更喜欢open-uri选项,因为它抽象了很多这些细节。

更新2

const http = require('http');

http.get('http://www.MyWebSite.com/Data/WOjson/02152018.json', (res) => {
  // deal with your status code etc here
  ...

  let data = '';

  res.on('data', (chunk) => {
    data += chunk; // append chunk to data
  });

  resp.on('end', () => {
    // this is where the rest of your code could be called. there are several approaches to calling here, either abstracting the remaining work to a function and pass in the data or wrapping the http call with a promise etc. For now, let's log the data
    const parsedData = JSON.parse(data)
    console.log( parsedData );
    ...
    parsedData.forEach(...)
  });

}).on("error", (err) => {
  console.log("Error occured: " + err.message);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM