当我在 node.js 中读取 JSON 文件时,非英语字符显示为“?”而不是原始字符。
流的结果已经采用了错误的字符集。
var fs = require('fs');
var path = require('path');
var stream = fs.createReadStream(path.join(__dirname,'../data.json'), 'utf8');
stream.on('error', function (error) {
response.status(500).send({ msg: error.message });
})
stream.pipe(response);
}
}
文件示例:
{
data: [
{"id":"111","name":"Dr. Per Änglund","phone":"7350-01794"},
{"id":"22","name":"Lars Änglund","phone":"1942-463945"}
]
}
最佳答案
您需要考虑encoding您尝试读取的文件的名称。
假设您使用读取文件
fs.readFile("test.txt", function(err, data) {
console.log( data );
});
您只需添加 'utf8'
参数即可指定您正在尝试读取 UTF-8文件:
fs.readFile("test.txt", 'utf8', function(err, data) {
console.log( data );
});
另请参阅this question .
关于javascript - 如何读取非英文字符,如: "Ä,ö" from file in node. js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43748438/