Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js Nodejs流CSV,在postgres中创建表并使用COPY FROM导入_Node.js_Postgresql_Csv - Fatal编程技术网

Node.js Nodejs流CSV,在postgres中创建表并使用COPY FROM导入

Node.js Nodejs流CSV,在postgres中创建表并使用COPY FROM导入,node.js,postgresql,csv,Node.js,Postgresql,Csv,有没有一种好方法可以将流形式的大型CSV(4GB+)放入NodeJS中的postgres db中 特别是,我想使用第一行(标题行)并在此基础上创建一个create查询。然后我想将文件的其余部分流式传输到from语句的副本 如果我只想发送到copy命令,这是可行的,例如: function copyStreamIntoTable (inputStream) { var deferred = Q.defer(); pg.connect("pg://postgres@localhost/npi

有没有一种好方法可以将流形式的大型CSV(4GB+)放入NodeJS中的postgres db中

特别是,我想使用第一行(标题行)并在此基础上创建一个create查询。然后我想将文件的其余部分流式传输到from语句的副本

如果我只想发送到copy命令,这是可行的,例如:

function copyStreamIntoTable (inputStream) {
  var deferred = Q.defer();
  pg.connect("pg://postgres@localhost/npi_demo", function (err, client) {
    var s = client.copyFrom("COPY hptc (code, type, classification, specialization, definition, notes) FROM STDIN WITH CSV HEADER");

    inputStream.pipe(through(function (data) {
      this.queue(data.toString("ascii"));
    })).pipe(s).on('close', function () {
      deferred.resolve();
    });
  });

  return deferred.promise;
}
但是我希望流读取第一行,然后运行create查询。创建查询完成后,我想将流的其余部分流式传输到copyFrom


有没有一种优雅的方法可以做到这一点?对于nodejs和streams,我还是一个相对较新的人。

对我的问题找到了一个更普遍的答案:

var fs = require('fs'),
    through = require('through'),
    split = require('split');

var inFile = fs.createReadStream('./lines'),
    outFile = fs.createWriteStream('./out'),
    headers;

var th = through(function (data) {
  if (typeof headers === "undefined") {
    headers = data;
    th.pause();
    setTimeout(function () { th.resume(); }, 5000);
  } else {
    this.queue(data + "\n");
  }
});

inFile.pipe(split())
  .pipe(th)
  .pipe(outFile)
  .on("close", function () {
    console.log("had headers: " + headers);
  });
其中,通过和拆分是npm安装的流帮助程序

如果填充内容为:

one
two
three
输出将是
had headers:one
,输出文件将包含内容

two
three

在我的特定问题的上下文中——超时将被查询db来创建表所取代,而写入out文件将被替换为写入copyFrom流。

检查node.js的PostgreSQL接口是否在其API中明确支持
COPY
。如果可能的话,你会想使用任何这样的支持,而不是试图直接使用
COPY
语句。@CraigRinger谢谢——我会查出来的。顺便说一句,我对节点中的流非常困惑。。。我知道我可以用readline之类的东西来阅读第一行。。。我可以用readline把剩下的部分写到postgres流中。。。但是为了正确地尊重pg施加的背压,除非我使用pipe@MichaelWasser嘿,我是新来的节点,我有同样的问题,你能给我发送代码或稍微解释一下这个酷,谢谢。你知道有没有关于CSV大小的建议?您是否将文件拆分为多个csv字符串或仅一个csv字符串?有记录吗?没有具体的分割方法——我用这种方法导入了一个4.5GB的csv