Search code examples
javascriptnode.jsencodefsbig5

node.js fs.writeFileSync() How to set encoding to big5?


the fs.writeFileSync encode default is UTF 8 I can't set the encode to big5. The documentation does not mention those encoding support. If this function does not support BIG5, what can I do?

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

When I set encoding(var encode='big5';) BIG5, the server generates an error.


Solution

  • To use an encoding that isn't standard with Node Core. You can use iconv-lite.

    It adds support for additional encodings including big5, here 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