The example in this article describes the method of batch modifying the file encoding format with JavaScript. Share it with everyone for your reference. The details are as follows:
Summary:
Recently, when I was making a manual, I encountered a problem of "garbled documents". After checking the files, I found that the file encoding was wrong. There were more than 100 files in total. It would be tragic if I used an editor to save them as utf8. So I wrote a program to modify the file encoding format in batches.
Code:
//Introduction package
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 whether the element is in the array
* @date 2015-01-13
* @param {[String]} elem [the element to be 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 [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, and the same file cannot be operated multiple times, otherwise garbled characters will appear.
The complete code can be downloaded from this site by clicking here.
I hope this article will be helpful to everyone’s JavaScript programming design.