【问题标题】:NodeJS How can i read large CSV/Text files from remote server without saving it to disk?NodeJS 如何从远程服务器读取大型 CSV/文本文件而不将其保存到磁盘?
【发布时间】:2019-11-14 10:29:02
【问题描述】:

我正在使用request 模块来获取一个包含 70K 行的大型 CSV 文件。 但是,正文中只显示了约 500 行。

代码如下:

request({
        url: "https://somedomain.com/path/to/file.csv",
        method: "GET"
    } , function (error, response, body) {
        if (error)
            console.error(error);
        else if(body && util.isString(body)){
            let dataArr = body.split("\n");
            console.log(dataArr.length);//Expected 70K, actual ~500
        }
    });

我想我需要使用某种类似于这样的流:

request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'));

但是,我不需要将其保存到磁盘,我正在使用它来构建 MongoDB 查询,例如:

let mongoQuery = {username: {$in:dataArr}}//dataArr should include 70K elements, each element is a string containing up to 60 chars.

有人能指出我正确的方向吗?

【问题讨论】:

    标签: node.js node-request


    【解决方案1】:

    我最终这样做了:(虽然我认为这样做有一种更优雅的方式。)

        let csvstream = request("https://somedomain.com/path/to/file.csv").pipe(fs.createWriteStream('/tmp/file.csv'));
        csvstream.on('finish', function () {
            let instream = fs.createReadStream('/tmp/file.csv');
            let outstream = new stream;
            let rl = readline.createInterface(instream, outstream);
    
            rl.on('line', function(line) {
                dataArr.push(line);
            });
    
            rl.on('close', function() {
                //mongoDB call using dataArr.... 
            });
        });
        csvstream.on('close', function () {
            console.log("close");
        });
        csvstream.on('error', function (error) {
            console.error(error);
        });
    

    【讨论】:

      【解决方案2】:

      您可以使用 Papa Parser 来解析大型 CSV 文件:

      function csvFileData(data) {
          console.log(data);
      }
      
      function remoteCSVFileParse(url, callBack) {
          Papa.parse(url, {
              download: true,
              dynamicTyping: true,
              complete: function(results) {
                  csvFileData(results.data);
              }
          });
      }
      
      remoteCSVFileParse("http://yourRemoteFile.com/Path/filename.csv", csvFileData);
      

      请参考:https://www.papaparse.com/docs#remote-files

      【讨论】:

        猜你喜欢
        • 2018-05-14
        • 1970-01-01
        • 2023-03-30
        • 2020-06-23
        • 1970-01-01
        • 2011-03-26
        • 1970-01-01
        • 2012-07-01
        • 2010-11-09
        相关资源
        最近更新 更多