gpt4 book ai didi

javascript - 将变量传递到 NodeJS 需要设置吗?

转载 作者:行者123 更新时间:2023-12-02 23:25:03 25 4
gpt4 key购买 nike

在我的nodeJS应用程序中,我尝试构建一个连接到我的外部服务的帮助程序库。

我想去


const client = require('./myService')(serviceKey);

在应用程序中我希望能够调用多个函数,例如:


var healthcheckState = client.healthcheck();
var functionOneBool = client.someFunction('variable0','variable1');

我发现了几篇关于如何做到这一点的帖子; How to pass variables into NodeJS modules? How can I pass a variable while using `require` in node.js?

但我不知道如何适应它们。

这是 myService.js


module.exports = function(serviceKey) {
var modules = {};
modules.healthcheck = {
function(){
console.log('I have a heartbeat!');
}
};
return modules;
};

当我尝试运行时:


const client = require('./myService')('abc123');
client.healthcheck();

我被告知client.healthcheck不是一个函数

我哪里出错了?

最佳答案

您的代码中存在语法错误。您正在创建一个 modules 对象,并在模块 Object 中创建一个没有任何键的对象,并将 function 作为值。

基本上你正在制作: obj = { healthcheck: { func } }; 你需要它不是 obj = { healthcheck: func }

module.exports = function(serviceKey) {
const modules = {};
modules.healthcheck = function(){
console.log('I have a heartbeat!');
}
return modules;
};

关于javascript - 将变量传递到 NodeJS 需要设置吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56781033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com