在expressjs中轻松使用助手类

我正在使用一个漂亮的准系统expressjs应用程序,并希望添加一个库/帮手来存储一些有用的代码。 理想情况下,我希望它能作为一个模块工作。 但是,我无法得到它的工作。 这是我得到的:

// helpers/newlib.js var NewLib = function() { function testing() { console.log("test"); } }; exports.NewLib = NewLib; 

 // controllers/control.js var newlib = require('../helpers/newlib').NewLib; var helper = new NewLib(); helper.testing(); 

我得到的错误是ReferenceError: NewLib is not defined 。 我根据我下载的另一个简单模块,遵循devise模式( exports如何工作)。

我究竟做错了什么?

你的代码有两个问题。

首先,你将NewLib函数从helpers / newlib.js分配newlib var,所以你应该使用new newlib()而不是new NewLib()

 // controllers/control.js var newlib = require('../helpers/newlib').NewLib; var helper = new newlib(); // <--- newlib, not NewLib helper.testing(); 

或者您可以将您的variables重命名为NewLib

 // controllers/control.js var NewLib = require('../helpers/newlib').NewLib; var helper = new NewLib(); // <--- now it works helper.testing(); 

其次, testingfunction不能在构造函数范围外访问。 您可以通过将其分配给this.testing来使其可访问,例如:

 // helpers/newlib.js var NewLib = function() { this.testing = function testing() { console.log("test"); } };