Skip to content

Instantly share code, notes, and snippets.

@struCoder
Created December 25, 2016 13:28
Show Gist options
  • Save struCoder/efbe112e8bbed7a16ffb41a8907a21a0 to your computer and use it in GitHub Desktop.
Save struCoder/efbe112e8bbed7a16ffb41a8907a21a0 to your computer and use it in GitHub Desktop.
遍历文件夹将gbk编码的文件专为utf8
'use strict';
const fs = require('fs');
const iconv = require('iconv-lite');
const path = require('path');
const p = console.log;
function readText(path) {
let buf = fs.readFileSync(path);
return iconv.decode(buf, 'gbk');
}
function writeFile(path, data) {
return fs.writeFileSync(path, data);
}
function load(rootPath) {
let files = fs.readdirSync(rootPath);
for(let i = 0; i < files.length; i++) {
if(files[i] !== '.DS_Store') {
let currentFilePath = path.join(rootPath, files[i]);
let stat = fs.statSync(currentFilePath);
if(stat.isDirectory()) {
load(currentFilePath)
} else {
let data = readText(currentFilePath);
let newFile = currentFilePath.replace('.txt', '.c.txt');
writeFile(newFile, data);
fs.unlink(currentFilePath);
}
}
}
}
// run
p('convert start.');
load(`${__dirname}/sentiment`);
p('convert end.');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment