node.js - 如何在nodejs的库中收集用户定义的函数?

标签 node.js

我有几个functions但我不知道如何在 Libary 中收集用户定义的函数以便在 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..);

看看https://www.sitepoint.com/object-oriented-javascript-deep-dive-es6-classes/

关于node.js - 如何在nodejs的库中收集用户定义的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46181108/

相关文章:

javascript - "trampoline"方法之间的区别

javascript - Rocket.Chat 构建失败,错误为 "Cannot find module ' ../build/Release/sharp.node' "

javascript - 如何根据操作码分离捕获的错误 (discord.js)

node.js - 模块别名包的智能感知

javascript - Ajax 在 POST 上发布 404

node.js - ioredis 错误 : connect ETIMEDOUT - Can't get connection to local redis server

node.js - 多边形内的 Mongoose 地理查询

angularjs - 多 webpack-dev-server/client 中出现错误?http ://localhost:4200

node.js - 渲染页面时不添加样式

javascript - 在 Azure Function 上使用 web3.js 调用以太坊