Because node. JS supports only the following encodings: UTF8, UCS2, ASCII, binary, base64, Hex, do not support encodings such as Chinese GBK or GB2312,
Therefore, if you want to read and write Chinese content, you must use additional modules: Iconv-lite
Note: node's Iconv module, only support Linux, does not support windows, so to use pure JS Iconv-lite, another: the author said Iconv-lite performance is better, specific reference git site: iconv-lite
Note 2: I am in the test read and write files, always can not write the Chinese file, has been garbled, read normal, later colleagues help me to find: JS file encoding format is ANSI,nodejs code file must be UTF8 format
1. Installation module: NPM Install Iconv-lite
2. Demo code, copy the following code into a file, assuming it is ch.js (Note: JS file must be saved in UTF8 encoding format):
Load the file system read-write module var fs = require (' FS ');//Load Code conversion module var iconv = require (' Iconv-lite '); var file = "C:\\a.txt", WriteFile (file), ReadFile (file), function WriteFile (file) { //test in Chinese var str = "\r\ n I am a man hello myself! "; Convert Chinese to byte array var arr = iconv.encode (str, ' GBK '); Console.log (arr); AppendFile, if the file does not exist, will automatically create a new file //If using WriteFile, then delete the old file, write the new file directly fs.appendfile (file, arr, function (err) { if (err) console.log ("fail" + err); else console.log ("Write file OK"); }); function ReadFile (file) { fs.readfile (file, function (err, data) { if (err) console.log ("Read file fail" + Err ); else{ //Read success //output byte array console.log (data); Convert the array to GBK var str = iconv.decode (data, ' GBK '); Console.log (str); } );}
3, with Node.exe implementation of this JS file, the results are as follows:
C:\>node ch.js<buffer 0d 0a CE d2 CA C7 D2 BB b8 f6 C8 CB 6c 6c 6f 6d All in 6c 21> write file Ok<buffer 0d 0a CE d2 CA C7 D2 BB b8 f6 C8 CB 6c 6c 6f 6d All-in-one 6c 21> I am a person Hello myself! C:\>