无法在nodejs 12中的lambda上导入csv解析

xggvc2p6  于 2022-12-29  发布在  Node.js
关注(0)|答案(2)|浏览(133)

我正在写一个代码,需要对lambda进行csv解析。运行时是节点12.x。
我通过npm 6.14.10(节点v12.20.1)安装了以下模块

{
  "name": "data_analysis_node",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "aws-sdk": "^2.1282.0",
    "csv-parse": "^5.3.3",
    "fs": "0.0.1-security"
  }
}

然后我压缩了一个node_modules目录,上传它,将它附加到一个层,将该层应用于函数,并编写了以下代码。
index.js

const AWS = require('aws-sdk');
const parse = require('csv-parse/lib/sync'); 
const fs = require('fs');

exports.handler = async (event) => {
    console.log('fine')
};

但它一直不工作,并显示以下错误。

2022-12-26T14:28:45.472Z    undefined   ERROR   Uncaught Exception  {
"errorType":"Runtime.ImportModuleError"
,"errorMessage":"Error: Cannot find module 'csv-parse/lib/sync'\nRequire 
stack:\n- /var/task/index.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js","stack":["Runtime.ImportModuleError: Error: Cannot find module 'csv-parse/lib/sync'","Require stack:","- /var/task/index.js","- /var/runtime/UserFunction.js","- 
/var/runtime/index.js","    at _loadUserApp (/var/runtime/UserFunction.js:100:13)","    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","    at Object.<anonymous> (/var/runtime/index.js:43:30)","    at Module._compile (internal/modules/cjs/loader.js:999:30)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)","    at Module.load (internal/modules/cjs/loader.js:863:32)","    at Function.Module._load (internal/modules/cjs/loader.js:708:14)","    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)","    at internal/main/run_main_module.js:17:47"]}

我重新检查了node_modules中的,并确认了csv解析的路径是正确的。

我还注解掉了imports csv-parse这一行,它没有输出任何错误,似乎导入其他模块也很好。

const AWS = require('aws-sdk');
//const parse = require('csv-parse/lib/sync'); 
const fs = require('fs');

exports.handler = async (event) => {
    console.log('fine')
};

我已经堆了3到4个小时,所以任何建议都是有帮助的。

ghhkc1vu

ghhkc1vu1#

为NodeJS创建Lambda图层时,zip文件中的结构应为nodejs/node_modules/,而不仅仅是node_modules/可选地,对于多个版本,您可以将nodejs/nodeXY/node_modules/放置在documentation中阅读有关Lambda图层的详细信息

68bkxrlz

68bkxrlz2#

像这样的东西有用吗?

const csvParse = require('csv-parse');
// do whatever with csvParse

可能是与csv解析API存在命名冲突

编辑

根据docs,您需要从csv-parse/sync而不是csv-parse/lib/sync获取解析模块
以下方法应该有效:

const parse = require('csv-parse/sync');

当从csv-parse/lib/sync请求时,我收到了与您相同的错误,当从csv-parse/sync请求时,它工作正常

相关问题