Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

express 路由怎么传递或者接收到node内置模块fs读取文件中的内容?

网页用的是express,然后用fs读取了一个test.txt文件的内容,现在想把这个内容显示到页面中,那个路由怎么传值啊?麻烦告知相关资料,我查查看。。谢谢了
比如我在app.js里写了。

fs.readFile('text.txt', function (err, data) {
   if (err) {
       return console.error(err);
   }
  console.log(data.toString());
});

怎么把这个data这个值传到路由routes的text_info.js里?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

比如:
创建一个file.js

代码:

exports.readFile = function(callback){
    fs.readFile('text.txt', function (err, data) {
       if (err) {
           return callback(err);
       }
     callback(null,data.toString());
    });
}

routes的text_info.js 例如

var express = require('express');
var router = express.Router();
var readFile = require('./file');
router.get('/file',function(req,res){
    
    readFile.readFile(function(err,data){
        if (err) {
           console.error(err);
       }
       res.send(data)
    })
})

module.exports = router;

以上是实例代码,具体的你可以自己随意组装


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...