gpt4 book ai didi

Node.js 重用函数

转载 作者:太空宇宙 更新时间:2023-11-03 23:45:15 25 4
gpt4 key购买 nike

我在文件 hello.js 中编写了一个函数

<小时/>
dep1=require('dependency');
function hello(Args, callback){
modifiedData= dep1.someFunction(Args);
console.log(modifiedData);
callback(modifiedData);
}
module.exports=hello;
<小时/>

我如何在其他文件中重用此函数?

h=require("./hello");
h.hello("Howdy!", function(err,args){
do something;
}

有什么指点吗?

最佳答案

这看起来可以接受,尽管有点难以阅读。但是,当您的回调将 err 作为第一个参数时,请确保发送 null 对象作为第一个参数:

callback(null, modifiedData);

当您使用module.exports时,模块本身可以作为该函数调用。因此,您将像这样重用该函数:

h = require("./hello");
h("Howdy!", function(err, args) {
//do smth
});

否则,为了使您的示例正常工作,只需删除 module. 并添加名称(可以是不同的名称):

exports.hello = hello;

关于Node.js 重用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14156552/

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