This article will share with you a piece of code, mainly to solve a problem encountered in the project. it is very practical to convert GBK encoding into UTF8 in batches and we recommend it to you. Abstract:
Recently, I encountered a problem when creating a manual: 'document garbled '. after checking the file, I found that the file encoding is incorrect. there are more than 100 files in total. if you use the editor to save it as utf8, then we are miserable. So I wrote a program to modify the file encoding format in batches.
Code:
The code is as follows:
/**
* Modify the file encoding format, for example, converting GBK to UTF8
* Supports multi-level directories.
* @ Param {String} [root_path] [file path for transcoding]
* @ Param {Array} [file_type] [format of the file to be transcoded, such as html file]
* @ Param {String} [from_code] [file encoding]
* @ Param {String} [to_code] [Object encoding]
*/
// Introduce the package
Var fs = require ('Fs '),
Iconv = require ('iconv-lite ');
// Global variable
Var root_path = './html ',
File_type = ['HTML ', 'htm'],
From_code = 'gbk ',
To_code = 'utf8 ';
/**
* Determine whether the element is in the array.
* @ Date 2015-01-13
* @ Param {[String]} elem [searched element]
* @ Return {[bool]} [description]
*/
Array. prototype. inarray = function (elem ){
"Use strict ";
Var l = this. length;
While (l --){
If (this [l] === elem ){
Return true;
}
}
Return false;
};
/**
* Transcoding functions
* @ Date 2015-01-13
* @ Param {[String]} root [encoding file directory]
* @ Return {[type]} [description]
*/
Function encodeFiles (root ){
"Use strict ";
Var files = fs. readdirSync (root );
Files. forEach (function (file ){
Var pathname = root + '/' + file,
Stat = fs. lstatSync (pathname );
If (! Stat. isDirectory ()){
Var name = file. toString ();
If (! File_type.inarray (name. substring (name. lastIndexOf ('.') + 1 ))){
Return;
}
Fs. writeFile (pathname, iconv. decode (fs. readFileSync (pathname), from_code ),{
Encoding: to_code
}, Function (err ){
If (err ){
Throw err;
}
});
} Else {
EncodeFiles (pathname );
}
});
}
EncodeFiles (root_path );
Summary:
The above program supports multi-level directories. the same file cannot be operated multiple times; otherwise, garbled characters may occur.
Complete Code: Complete.
Isn't it very good? I hope everyone will like it. leave a message if you have any questions.