重构NodeJs函数
我有一个大app.js
文件,并希望拆分代码。 我把所有的路线放到一个名为routes.js
的模块中
module.exports = function(app){ app.get('/', function (req, res) { res.redirect('/page1'); }); app.get('/page1', function (req, res) { res.render('page1'); }); app.get('/page2/:id', function (req, res) { res.render('page2', { val: Number(req.params.id) }); }); }
并在我的app.js我打电话
const routes = require('./Server/routes')(app);
所以这工作正常。
我有一些function
function loadData(id, callback) { fs.readFile('./database.json', 'utf8', function (err, data) { var json = JSON.parse(data); var arr = json.arr; var obj = arr.find(e => e.id === Number(id)); callback(obj); }); }
并希望将它们放在单独的文件中。 我怎样才能做到这一点? 我能够导出一个function,但我怎样才能导出多个?
喜欢
module.exports = function(){ function sayHello(){ console.log("Hello"); } function calc(){ return 5 + 7; } }
需要模块和呼叫
myModule.sayHello(); var num = myModule.calc();
在你的新模块中,你可以导出一个对象并在对象中定义你的函数
module.export = { sayHello: function() { console.log("Hello"); }, calc: function() { return 5 + 7; } } // usage: const mymodule = require('path/to/your/file');
你也可以导出一个函数,并在原型中定义你需要的函数
function mymodule(someArgsIfNeeded) { // do some initialization } mymodule.prototype.sayHello = function() { console.log("Hello"); } mymodule.prototype.calc = function() { return 5 + 7; } module.export = mymodule // usage: const mymodule = require('path/to/your/file')(someArgsIfNeeded);
- 很多很多自我参考在sequelize在twitter像web应用程序
- 如何在callback函数中使用express.send(例如nodejs中的mysqljs使用)
- 使用connect.query()查询nodejs中的url
- jQuery,为触发事件的元素findselect器
- 如何在async.each中包含async.waterfall的外部函数中调用async.each
- Node.JS – 简单的Socket.IO示例不起作用。 获取debugging服务的静态内容/socket.io.js(Mac OSX / Localhost)
- sinon存根不替代function
- 如何使用nodejs部署angular度的应用程序
- JavaScript平台独立行分隔符