Node JS Stream Only仅适用于第一次迭代

时间:2018-04-21 23:14:51

标签: node.js parsing filestream node-modules

我有一个简单的节点应用程序,可以将csv文件解析为字符串。在我的服务器文件中,我调用一个运行的模块生成一个流并将其传递到我的解析器中。 问题是代码在第一次运行时运行良好,但在此之后失败。我得到了一个“Write after End”错误,所以我相信在每次使用后流或解析器变量没有被正确重置有问题。谢谢你的帮助!

const express    = require('express');
const app        = express();
const path       = require('path');
const port       = process.env.PORT || 3000;
const formidable = require('formidable');
const parser     = require('./csvparse.js');
const fs         = require('fs');



//send the index page on a get request
app.listen(port, () => console.log('Example app listening on port: ' + port));
app.get('*', (req, res) => res.sendFile(path.join(__dirname + "/index.html")));

app.post('/upload', function(req, res) {
  //upload the file from the html form
  var form = new formidable.IncomingForm();
  form.parse(req,function(err, fields, files) {
    if (err) throw err;
    //get the path to the uploaded file for the parser to use
    var filePath = files.spinFile.path;
    parser(filePath, function(data) {
        if (data == null) {
            res.sendFile(path.join(__dirname + "/index.html"));
        }   
            res.send("<code>" + data + "</code>");
    });
  });
});

模块导出功能如下所示:

module.exports = function(filePath, cb) {

    var stream = fs.createReadStream(filePath);
    stream.pipe(parser);
    //when the stream is done, songsLog is complete and ready to be returned
    stream.on('close', function() {
        cb(songsLog);
    });
};

1 个答案:

答案 0 :(得分:0)

尝试在另一个函数中包装module.exports的内容。

module.exports = function(filepath, cb) {
    function parse(filepath) {
        const stream = fs.createReadStream(filepath)
        etc...
    }
    return {
        parse
    }
}

然后从你的路线,调用parser.parse('file.txt')你应该有一个新的读取流。

相关问题