Skip to content

Instantly share code, notes, and snippets.

@okunishinishi
Last active December 29, 2015 03:49
Show Gist options
  • Save okunishinishi/7610627 to your computer and use it in GitHub Desktop.
Save okunishinishi/7610627 to your computer and use it in GitHub Desktop.
ディレクトリ内のファイル全てを、拡張子以外全角に変換する。  例)勤怠表_T01234_奥西.excel => 勤怠表_T01234_奥西.txt
#!/bin/env node
var exec = require('child_process').exec,
fs = require('fs'),
path = require('path'),
here = process.cwd();
(function (bin_name) {
var resolve = path.resolve,
mkdir = fs.mkdir;
var bin = resolve(here, bin_name + '.js');
var testDir = resolve(here, ['test', bin_name , new Date().getTime()].join('-'));
mkdir(testDir, function (err) {
if (err) console.error(err);
var testFiles = [
"すべて全角N1234_.txt",
"半角込みN1234_B567789_.txt"
];
testFiles
.map(function (filename) {
return resolve(testDir, filename);
})
.forEach(function (filepath) {
fs.writeFileSync(filepath, 'ファイルの中身');
});
var command = ["node", bin, testDir].join(' ');
exec(command, function (err, stdout, stderr) {
if (err) console.error(err);
if (stderr) console.error(stderr);
console.log(stdout);
fs.readdir(testDir, function (err, filenames) {
// filenames = filenames.sort();
console.log("filenames", filenames);
});
});
});
})("to_zenkaku_filenames");
#!/bin/env node
var fs = require('fs'),
path = require('path'),
argv = process['argv'];
var dirpath = argv[2];
var PATTERNS = {
ZENKAKU: /[!-~]/g,
HANKAKU: /[\!-\~]/g
};
console.log('argv',argv);
fs.exists(dirpath, function (exists) {
if (!exists) {
console.error(dirpath, 'not exists!');
return;
}
var resolve = path.resolve,
extname = path.extname,
rename = fs.rename;
function hasHankaku(string) {
return string && string.match(PATTERNS.HANKAKU);
}
function toZenkaku(string) {
return string.replace(PATTERNS.HANKAKU, function (s) {
return String.fromCharCode(s.charCodeAt(0) + 0xFEE0);
});
}
fs.readdir(dirpath, function (err,filenames) {
if(err) console.error(err);
filenames.forEach(function (filename) {
var extension = extname(filename),
extension_less = filename.replace(new RegExp(extname(filename) + "$"), '');
var needsConvert = hasHankaku(extension_less);
if (!needsConvert) return;
var old_filepath = resolve(dirpath, filename),
new_filepath = resolve(dirpath, toZenkaku(extension_less) + extension);
rename(old_filepath, new_filepath, function () {
console.log('convert file:', old_filepath, 'to', new_filepath);
});
});
});
});
process.on('exit', function () {
console.log('done!');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment