【问题标题】:How to invoke a function in index.js written in Node.js如何调用用 Node.js 编写的 index.js 中的函数
【发布时间】:2020-05-14 13:51:52
【问题描述】:

我是 NodeJS 的新手,这可能是一个非常基本的问题,但如果您能在这里为我提供帮助,我将不胜感激。

以下是我的 index.js 文件:-

'use-strict';

const { myauth } = require('./src/authorizer');

let response;

exports.handler = (event, context, callback) => {
    logger.info('hello....function invoked');
    try {
        logger.info(event);
        const resp = myauth(event, context, callback, logger);
        response = {
                'statusCode': 200,
                'body': JSON.stringify({
                    data: resp
                })
         }
    } catch (err) {
        logger.error('handler func', err);
        response = {
            'statusCode': 500,
            'body': JSON.stringify({
                message: err,
                data: false
            })
        }
    }
    return response;
}

Package.json:-

    {
  "name": "authorizer",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/node": "^13.13.5"
  },
  "devDependencies": {
    "chai": "^4.2.0",
    "mocha": "^6.1.4"
  }
}

当我执行 npm start 之类的命令时,它不会调用 Index.js 文件中写入的函数内部的逻辑。

请告诉我如何执行此功能。谢谢

【问题讨论】:

  • 你期望它做什么?您有一个导入并定义了一个导出函数,但该函数永远不会被调用
  • 你到底想做什么?写一个网络服务? Node.js 本身就像 C++、Python 和 Ruby 这样的普通语言——它不服务于像 PHP 这样的网站。您将需要使用 Http 模块或使用 Express 或 Connect 等框架编写服务器逻辑
  • 如果你真的想做这样的事情,这个答案可能会做到:stackoverflow.com/questions/34653829/… 但就像其他人所说的那样,我不认为这是你想要或需要走的路.

标签: javascript node.js npm ecmascript-6


【解决方案1】:

我不确定“调用”是什么意思,我想你想将返回的函数结果分配给你的变量。为此,您可以使用此 javascript sintax 自动调用您的函数。

exports.handler = ((event, context, callback) => {
    logger.info('hello....function invoked');
    try {
        logger.info(event);
        const resp = myauth(event, context, callback, logger);
        response = {
                'statusCode': 200,
                'body': JSON.stringify({
                    data: resp
                })
         }
    } catch (err) {
        logger.error('handler func', err);
        response = {
            'statusCode': 500,
            'body': JSON.stringify({
                message: err,
                data: false
            })
        }
    }
    return response;
})();

告诉我。谢谢!

【讨论】:

    猜你喜欢
    • 2013-01-28
    • 2022-08-18
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2016-07-02
    相关资源
    最近更新 更多