如何在Node.js中流化文件并将编码保持为ansi(windows-1252) [英] How do I stream a file and keep the encoding as ansi (windows-1252) in Node.js
问题描述
我使用Formidable将文件上传到我的Node-js webserver(本地安装进行测试)。该文件在ansi(iso-8859-1)之前,我上传它,它仍然是当它已经上传,我已经使用记事本++检查该文件。
I use Formidable to upload a file to my Node-js webserver (local installation for testing). The file is in ansi (iso-8859-1) before I upload it, and it still is when it has been uploaded, I've checked the file using Notepad++.
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
csv
.fromPath(files.upfile.path, {headers: true})
.on("record", function(data){
console.log(data.adresse);
})
.on("end", function(){
console.log("done");
});
res.end(console.log("form done"));
});
一旦我使用流或插件(在这种情况下为fast-csv)节点fs流式传输内容,编码被打扰。看到下面的数据,?应该是丹麦字符ø。
As soon as I use a stream or a plugin(fast-csv in this case) that uses a node fs to stream the content, the encoding is botched. See the data below, the ? should be the danish character ø.
{adresse: 'Niver?d By, Karlebo'}
任何人都可以告诉我为什么?
Can anyone tell me why?
更新: strong>
Update:
它通过流式传输上传的文件并使用Iconv进行转换。
It worked by streaming the uploaded file and using Iconv to convert it.
router.post('/upload', function(req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
console.log(files.upfile.path);
var stream = fs.createReadStream(files.upfile.path);
var csvStream = csv({headers : true})
.on("record", function(data){
var db = req.db;
// Set our collection
var collection = db.get('bbrcollection');
// Submit to the DB
collection.insert(data, function (err, doc) {
//console.log(data);
if (err) {
// If it failed, return error
console.log("There was a problem adding the information to the database.");
}
});
})
.on("end", function(){
console.log("done");
});
stream
.pipe(new Iconv('WINDOWS-1252', 'UTF-8'))
.pipe(csvStream);
});
res.render('upload', { title: 'upload file'});
});
推荐答案
您必须将编码转换为utf8才能使用javascript中的内容。 iconv 和 iconv-lite 应该能够为你做。
You have to convert the encoding to utf8 to use the contents in javascript. Both iconv and iconv-lite should be able to do that for you.
这篇关于如何在Node.js中流化文件并将编码保持为ansi(windows-1252)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!