How to modify the file encoding format in batches using javascript
This article describes how to modify the file encoding format in batches using javascript. Share it with you for your reference. The details are as follows:
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:
Copy codeThe 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.
Click here to download the complete code.
I hope this article will help you design javascript programs.