This article describes the method of batch modifying file encoding format in JavaScript. Share it for your reference. The details are as follows:
summary:
Recently, I encountered a problem when I was making the manual 'document code'. After checking the file, I found that the file encoding was wrong, with more than 100 files in total. If I save it as utf8 with the editor, it would be sad. So I wrote a program myself to batch modify the file encoding format.
Code:
Copy the code as follows:/**
* Modify the file encoding format, for example: GBK to UTF8
* Supports multi-level directory
* @param {String} [root_path] [file path that needs to be transcoded]
* @param {Array} [file_type] [File format that requires transcoding, such as html file]
* @param {String} [from_code] [File encoding]
* @param {String} [to_code] [Target encoding of file]
*/
// Introduce 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 [Element being looked up]
* @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 directories, and the same file cannot be operated multiple times, otherwise garbled code will appear again.
The complete code can be downloaded by clicking here.
I hope this article will be helpful to everyone's JavaScript programming.