readFile返回合并在一起的所有行

时间:2016-04-10 12:58:43

标签: node.js

.get('/listscripts/:filename', function(req, res){
    fs.readFile(__dirname + '/../public/scripts/' + req.params.filename, 'utf8', function(err, content) {
        if (err) return;
        res.send(content);
    });
})

我尝试使用readFile返回文本文件的内容,但出于某种原因,它将所有行合并在一起。

因此,如果我正在阅读如下文件:

Line 1
Line 2
Line 3

然后readFile的输出将返回:

Line 1 Line 2 Line 3

有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:0)

您可以逐行阅读并操作并在最终回复中插入:

app.get('/listscripts/:filename', function(req, res){
   var result = [];   
   var readline = require('linebyline'),
       rl = readline((__dirname + '/../public/scripts/' + req.params.filename);
       rl.on('line', function (line, lineCount, byteCount) {
           console.log(lineCount, line, byteCount); // do something with the line of text
           result.push(line);            
    })
   .on('error', function (e) {
            console.log("error", e);
            // something went wrong
        })
   .on('end', function () {
       // All lines are read, file is closed now.
       res.send(result);    
   });

});