Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何在nodjs的库中收集用户定义的函数?_Node.js - Fatal编程技术网

Node.js 如何在nodjs的库中收集用户定义的函数?

Node.js 如何在nodjs的库中收集用户定义的函数?,node.js,Node.js,我有几个函数,但我不知道如何在library中收集用户定义的函数,以便在整个nodeJs项目中重用它们?您可以这样做: 在首选文件夹中,创建一个类似user.js的文件 然后,定义一个类,E6方式: class Users { //if you need a constructor, but it's not mandatory constructor(username,email,otherParamYouNeed){ this.username = username; this.email

我有几个
函数
,但我不知道如何在library中收集用户定义的函数,以便在整个nodeJs项目中重用它们?

您可以这样做: 在首选文件夹中,创建一个类似user.js的文件 然后,定义一个类,E6方式:

class Users {
//if you need a constructor, but it's not mandatory
constructor(username,email,otherParamYouNeed){
this.username = username;
this.email = email;
this.otherParamYouNeed = otherYouNeed
}

//then organize your user functions there

userFunctionThatDoesSomething(){
//do what you need
}
userFunctionThatDoesAnotherThing(){
 // do what you need
}
}

//then export the class
module.exports = {Users}
之后,在需要调用这些函数的文件中:

var {Users} = require ('/path/to/user.js');
//if you have constructor in your class
var user = new Users(username,email,otherParamYouNeed);
//if not
var user = new Users;
之后,您将能够在需要该类的文件中使用在该类中声明的函数,如:

user.userFunctionThatDoesSomething(etc..);

看一看

阅读一些源代码,看看“require(x)”是如何工作的——我想你也想做类似的事情。嗨@thegleep,我是编程新手。谢谢,我现在就做。