在下面找到一个完整的应用程序,该应用程序可以正确执行所需的任务:它将文件读取为流,将其解析为CSV,并将每一行插入数据库。
const fs = require('fs');const promise = require('bluebird');const csv = require('csv-parse');const pgp = require('pg-promise')({promiseLib: promise});const cn = "postgres://postgres:password@localhost:5432/test_db";const rs = fs.createReadStream('primes.csv');const db = pgp(cn);function receiver(_, data) { function source(index) { if (index < data.length) { // here we insert just the first column value that contains a prime number; return this.none('insert into primes values($1)', data[index][0]); } } return this.sequence(source);}db.task(t => { return pgp.spex.stream.read.call(t, rs.pipe(csv()), receiver);}) .then(data => { console.log('data:', data); } .catch(error => { console.log('ERROR:', error); });请注意,我唯一改变的是:使用library
csv-parse代替
csv,作为更好的选择。
增加了使用方法stream.read从SPEX库,它正确地供应可读与承诺使用流。



