Skip to content

Instantly share code, notes, and snippets.

@vsemozhetbyt
Last active April 1, 2016 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vsemozhetbyt/1b161eb635047e44e2bd to your computer and use it in GitHub Desktop.
Save vsemozhetbyt/1b161eb635047e44e2bd to your computer and use it in GitHub Desktop.
'use strict';
/******************************************************************************/
const fpath = process.argv[2];
if (!fpath) {
console.error('Add the file path, please.');
process.exit(1);
}
/******************************************************************************/
const fs = require('fs');
const inCoding = guessEncoding(fpath);
if (!inCoding) process.exit(1);
const outCoding = 'utf8';
const rl = require('readline').createInterface({
input: fs.createReadStream(fpath, inCoding),
terminal: false,
historySize: 0
});
const outfile = fs.openSync(fpath.replace(/(\.[^.]+)?$/, '.hw.txt'), 'w');
fs.writeSync(outfile, '\uFEFF', null, outCoding);
const bomRE = /^\uFEFF/;
const hwRE = /^[^#\s]/;
let lineNumber = 0;
/******************************************************************************/
rl.on('line', line => {
if (++lineNumber === 1) line = line.replace(bomRE, '');
if (hwRE.test(line)) {
fs.writeSync(outfile, `${line.trim()}\n`, null, outCoding);
}
});
/******************************************************************************/
function guessEncoding(fpath) {
try {
const fd = fs.openSync(fpath, 'r');
const bf = Buffer.alloc(2);
fs.readSync(fd, bf, 0, 2, 0);
fs.closeSync(fd);
return bf[0] === 0xFF && bf[1] === 0xFE ? 'utf16le' : 'utf8';
} catch(e) {
console.error(`Error: ${e.message}.`);
return null;
}
}
/******************************************************************************/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment