简体   繁体   English

如何在lambda函数中将文件夹添加为模块?

[英]How to add folder as module in lambda function?

So, I have serverless project, i would like to run function as below 所以,我有无服务器项目,我想运行如下功能

'use strict';
const report= require('./report');

module.exports.startAdMeta = (event, context) => {
  report.init();
  return "success";
}

I have problem with add "report" folder as module in handler.js. 我在处理程序.js中将“报告”文件夹添加为模块时遇到问题。 How to add module all file in lambda? 如何在lambda中添加模块所有文件?

Response: { "errorMessage": "Cannot find module 'report'", "errorType": "Error", "stackTrace": [ "Function.Module._load (module.js:417:25)", "Module.require (module.js:497:17)", "require (internal/module.js:20:19)", "Object. (/var/task/handler.js:2:35)", "Module._compile (module.js:570:32)", "Object.Module._extensions..js (module.js:579:10)", "Module.load (module.js:487:32)", "tryModuleLoad (module.js:446:12)", "Function.Module._load (module.js:438:3)" ] } 响应:{“ errorMessage”:“找不到模块'report'”,“ errorType”:“错误”,“ stackTrace”:[[Function.Module._load(module.js:417:25)“,” Module.require (module.js:497:17)“,”要求(internal / module.js:20:19)“,”对象。(/var/task/handler.js:2:35)“,” Module._compile( module.js:570:32)“,” Object.Module._extensions..js(module.js:579:10)“,” Module.load(module.js:487:32)“,” tryModuleLoad(模块。 js:446:12)“,” Function.Module._load(module.js:438:3)“]}

I do that by three steps. 我通过三个步骤来做到这一点。

1) add below lines to package.json 1) package.json添加到package.json

  "dependencies": {
    "report": "file:./report"
  }

2) install as npm package 2)安装为npm软件包

npm install

3) require it as normal node_modules. 3)要求它作为普通的node_modules。

const report= require('report');

Thankyou, solution of problem node js version upgrade. 谢谢,问题节点js版本升级的解决方案。 Upgraded to the latest version and solved. 升级到最新版本并解决。

Using FS: 使用FS:

You can import all files as modules with this snippet code: 您可以使用以下代码段将所有文件导入为模块:

var allModuls = new Map();

fs.readdir("./commands", (err, files) => {
  files.forEach(file => { // for each file in the directory "commands"

    if (file == 'main.js'){return;} //my main.js is inside the folder so I excluded it.

    var modulName = file.split(".")[0];
    var importedModul = require("./" + file );
    allModuls.set(modulName, importedModul );
  });
})

All modules will be accessible via : AllModuls.get([modulName]) 所有模块都可以通过以下方式访问:AllModuls.get([modulName])

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

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