Home >Web Front-end >JS Tutorial >nodejs batch modify file encoding format_node.js

nodejs batch modify file encoding format_node.js

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

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. If you use an editor to save them as utf8, it would be tragic. 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]
​*/
//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 [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.

Full code: https://github.com/baixuexiyang/coding, you can fork it under your own account. If there are bugs, please report them on the issue.

Isn’t it very good? I hope you all like it. If you have any questions, please leave a message.

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