nodejs模块 - 表达module.export - 如何将变量传递给其他文件?

时间:2016-11-20 20:03:31

标签: javascript node.js

问题是如何以最简单的方式将变量传递给其他js文件(没有任何路由只使用module.exports)。

我的文件结构看起来像这样(非常简单的流行结构):

ROUTES (folder)
--form.js
--test.js

VIEWS (folder)
--form.ejs
--test.ejs

index.js
package.json

index.js文件(标准快递应用文件):

var express = require('express');
var body_parser = require('body-parser');

var form = require('./routes/form.js');
var test = require('./routes/test.js');

var app = express();
app.set('view engine', 'ejs');
app.use(body_parser.urlencoded({extended:true}));

app.use('/', form);
app.use('/test', test);

var port = 3700;
var server_listen_on = app.listen(port, function()
{
    console.log('Server is listening on port: ' + port);
});

form.js文件:

var express = require('express');
var body_parser = require('body-parser');
var router = express.Router();

var preciousData = 'var precious_data - from form.js file';

module.exports =
{
    exportsPreciousData : preciousData,
    router : router
};

test.js文件:

var express = require('express');
var request = require('request');
var router = express.Router();

var requireFormjs = require('./form.js');//({exportsPreciousData : exportsPreciousData});


//console.log(requireFormjs.exportsPreciousData); // I guess console.log is faster then module.exports... but

router.get('/', function(req, res, next)
{
    res.render('welcome', {test : requireFormjs.exportsPreciousData});
});

// why this doesn't work - I need to use middleware function - could you provide simple working example?
//(I guessing that even if console.log print data after module.exports machinery I would still need middleware, right?)

module.exports = router;

welcome.ejs文件:

<!DOCTYPE html>
<html>
<head>
<title>welcome</title>

</head>
<body>

<%= test %>

</body>
</html>

...为什么它不起作用(没有表达一切正常)?

1 个答案:

答案 0 :(得分:0)

简单地让那些其他文件返回一个函数:

Test.js:

module.exports = function(preciousData) {
  // do everything here
  return router;
}

index.js:

var test = require('test.js')(preciousData);

通过调用test.js返回的函数并从该函数返回路由器

来传递数据