Node.js Read and write Chinese content file Operation __js

Source: Internet
Author: User
Tags readfile require

Because Node.js only supports the following encodings: UTF8, UCS2, ASCII, binary, base64, Hex, do not support encoding such as Chinese GBK or GB2312,

So if you want to read the Chinese content of a file in GBK or GB2312 format, you must use an extra module: iconv-lite


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 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 Chinese
    var str = "\ r \ n I am a person hello myself!";
    Convert Chinese to byte array
    var arr = iconv.encode (str, ' GBK ');
    Console.log (arr);
    
    AppendFile, if the file does not exist, it will automatically create a new file
    //If used 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 files fail + err );
        else{
            ///
            output byte array
            console.log (data) when reading successfully;
            Converts the array to GBK Chinese
            var str = iconv.decode (data, ' GBK ');
            Console.log (str);}}
    );


3, the use of Node.exe to execute 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 21>
Write file ok
<buffer 0d 0a CE d2 CA C7 D2 BB b8 f6 C8 CB 6c 6c 6f 6d 6c 21>

I'm a man hello myself!

C:\>

Note 1:node Iconv module, only support Linux, does not support windows, so to use pure JS Iconv-lite, another: the author said Iconv-lite performance better, specific reference to 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, and later my colleagues to help me find: JS file encoding format is ANSI,Nodejs code file must be UTF8 format

Note 3: If the program operation files, are stored in the UTF8 encoding format, then do not need to use the Iconv module, directly in the UTF8 format to read files, such as:

Parameter file, must be saved in UTF8 format, otherwise the Chinese will be garbled
function readFile (file) {
    //ReadFile's 2nd parameter represents the Read encoding format, if this argument is not passed, Returns a buffer byte array
    fs.readfile (file, "UTF8", function (err, data) {
        if (err)
            console.log ("Read file fail" + err);
        else{
            //Read successfully
            Console.log (data)//Directly output Chinese string
        }
    });

conclusion: When using Node.js development, both code files and other files to read and write are recommended to be saved using the UTF8 encoding format, which eliminates the need for additional module support

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.