Skip to content

Instantly share code, notes, and snippets.

@2no
Last active December 16, 2015 07:08
Show Gist options
  • Save 2no/5395987 to your computer and use it in GitHub Desktop.
Save 2no/5395987 to your computer and use it in GitHub Desktop.
grunt.file.write はファイルエンコーディングを指定して保存が可能だが、iconv-lite を使っている関係で SJIS などの保存は出来ない。 別途 iconv をインストールして対応する必要がある。 (ただし、libiconv にパッチをあてないと SJIS-win や EUCJP-win は扱えない)
// tasks/encoding.js
'use strict';
module.exports = function(grunt)
{
var Iconv = require('iconv').Iconv
, path = require('path')
;
grunt.registerMultiTask('encoding', 'Change the character set.', function() {
var options = this.options({
fromEncoding: grunt.file.defaultEncoding
, separator: grunt.util.linefeed
})
, toEncoding = this.data.toEncoding
;
grunt.verbose.writeflags(options, 'Options');
this.files.forEach(function(f) {
var validFiles = removeInvalidFiles(f);
writeFile(f.dest, concatOutput(validFiles, toEncoding, options));
});
});
function removeInvalidFiles(files)
{
return files.src.filter(function(filepath) {
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
}
else {
return true;
}
});
}
function concatOutput(files, toEncoding, options)
{
var code = files.map(function(filepath) {
return grunt.file.read(filepath);
}).join(grunt.util.normalizelf(options.separator));
return convertEncoding(code, toEncoding, options);
}
function convertEncoding(code, toEncoding, options)
{
try {
return new Iconv(options.fromEncoding, toEncoding).convert(code);
}
catch (e) {
grunt.log.error(e);
throw e;
}
}
function warnOnEmptyFile(path)
{
grunt.log.warn('Destination (' + path + ') not written because files were empty.');
}
function writeFile(path, output)
{
if (output.length < 1) {
warnOnEmptyFile(path);
}
else {
grunt.file.write(path, output);
grunt.log.writeln('File ' + path + ' created.');
}
}
};
'use strict';
module.exports = function(grunt) {
grunt.initConfig({
encoding: {
standardSetting: {
toEncoding: 'SJIS'
, files: {
'dest/result.txt': 'src/original.txt'
, 'dest/concat.txt': ['src/concat/*.txt']
}
}
, globToMultipleSetting: {
toEncoding: 'SJIS'
, expand: true
, flatten: true
, cwd: 'src'
, src: '**/*.txt'
, dest: 'dest'
, ext: '.sjis.txt'
}
}
});
grunt.loadTasks('tasks');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment