我是 node js 的新手。
我的本地系统中有一个 csv 文件,我想使用 Node js 将其上传到本地 PostgreSQL 数据库。
我正在尝试以下代码:
var csv = require('csv-stream');
var request = require('request');
var fs = require('fs');
// All of these arguments are optional.
var options = {
delimiter : '\t', // default is ,
endLine : '\n', // default is \n,
// by default read the first line and use values found as columns
// columns : ['Settlement Ref No.', 'Order Type','Fulfilment Type','Seller SKU','wsn'],
escapeChar : '"', // default is an empty string
enclosedChar : '"' // default is an empty string
}
var csvStream = csv.createStream(options);
fs.createReadStream('C:\\Users\\YAM\\Documents\\fk_starchi.csv').pipe(csvStream)
.on('error',function(err){
console.error(err);
})
.on('data',function(data){
// outputs an object containing a set of key/value pair representing a line found in the csv file.
// console.log(data);
})
.on('column',function(key,value){
// outputs the column name associated with the value found
// console.log('#' + key + ' = ' + value);
console.log('# ' + value);
})
它的阅读数据。 现在我想将它导入到 postgrsql 数据库中。
我在哪里可以获得教程或任何其他帮助来执行此操作。
最佳答案
我知道您想将此 cvs 文件导入 Postgres。
有两个步骤。读取文件。写入数据。
1) 读取您使用 csv-stream 完成的文件。我不太明白列事件的作用,但看起来“数据”事件是从哪里开始的。所以在此处添加您的代码。
2) 写入数据。
有两条路线:
a) 又快又脏。在“数据”事件中,使用字符串制作 SQL,然后使用像 node-postgres 这样的精简库运行它们.
var sql = 'INSERT INTO table VALUES (' data.this + ',' + data.that + ',' + data.theotherthing + ');';
查看此示例以获取 structure to start .您已经熟悉流,因此您只需要管理回调。
csv-stream 生成 SQL 语句的速度比 postgress 处理它们的速度快,因此您可能会遇到 1000 个并发请求。您可能希望将查询字符串成批地组合在一起,和/或使用 through2查询,等待,然后查询。
不这样做的原因是有人可以将 SQL 注入(inject)到 CSV 中并破坏您的数据库。
b) 执行此操作的明智方法(尤其是在处理未知 CSV 时)是使用像 sequelize 这样的 ORM。 .
没有复制/粘贴和完成。一个好的起点是阅读他们的 homepage .
关于javascript - 如何使用 Node js将csv文件导入postgresql?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30094919/