The examples in this article describe the ways in which JavaScript bulk modifies file encoding formats. Share to everyone for your reference. Specifically as follows:
Summary:
Recently in the production of a manual encountered a problem ' document garbled ', after viewing the file found that the file code is not correct, a total of more than 100 files, if the editor to save as UTF8, it will be sad reminders. So I wrote a program, batch modification file encoding format.
Code:
Copy Code code as follows:
/**
* Modify the file encoding format, such as: GBK turn UTF8
* Multi-level directory support
* @param {String} [root_path] [File path with transcoding required]
* @param {Array} [file_type] [file format that requires transcoding, such as HTML files]
* @param {String} [From_code] [Encoding of files]
* @param {String} [To_code] [target encoding of the file]
*/
Introducing Packages
var fs = require (' FS '),
Iconv = require (' Iconv-lite ');
Global variables
var root_path = './html ',
File_type = [' html ', ' htm '],
From_code = ' GBK ',
To_code = ' UTF8 ';
/**
* Determine if the element is within an array
* @date 2015-01-13
* @param {[String]} Elem [element found]
* @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 function
* @date 2015-01-13
* @param {[String]} root [encoded 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 directory, the same file can not be repeated operation, otherwise there will be garbled.
Complete code can click here to download the site.
I hope this article will help you with your JavaScript programming.