Home  >  Article  >  Web Front-end  >  How to batch modify file encoding format in javascript_javascript skills

How to batch modify file encoding format in javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:18:041335browse

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:

Copy code The code is as follows:
/**
* Modify the file encoding format, for example: GBK to UTF8
* Support multi-level directories
* @param {String} [root_path] [File path that needs to be transcoded]
* @param {Array} [file_type] [File format that needs to be transcoded, such as html file]
* @param {String} [from_code] [File encoding]
* @param {String} [to_code] [Target encoding of the file]
​*/

//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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn