node.js fs.writeFileSync()如何将编码设置为big5?

时间:2016-07-19 04:30:26

标签: node.js encode fs big5

fs.writeFileSync 编码默认为 UTF 8 我无法将编码设置为big5。 文档没有提到那些编码支持。 如果此功能不支持BIG5,我该怎么办?

var fs = require('fs');
var FilePath='./text.txt';
var Str='this is a test!';
var encode='utf8';
fs.writeFileSync(FilePath, Str, encode);

当我设置编码(var encode =' big5';)BIG5时,服务器会生成错误。

1 个答案:

答案 0 :(得分:2)

使用非standard with Node Core的编码。您可以使用iconv-lite

它增加了对其他编码的支持,包括big5here is the full list of encodings

const iconv = require('iconv-lite');
const fs = require('fs');
const stream = require('stream');

var Str = iconv.encode('This is a test', 'big5');

var readStream = new stream.PassThrough();
var writeStream = fs.createWriteStream('./text.txt');

readStream.once('error', (err) => { console.log(err); });    
readStream.once('end', () => { console.log('File Written'); });

readStream.end(Str); // write data to stream    
readStream.pipe(writeStream); // pipe data to file