Skip to content

Instantly share code, notes, and snippets.

@vsemozhetbyt
Created January 17, 2016 14:52
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/e63976b461bf97639939 to your computer and use it in GitHub Desktop.
Save vsemozhetbyt/e63976b461bf97639939 to your computer and use it in GitHub Desktop.
'use strict';
/******************************************************************************/
const path = process.argv[2];
const linesPerPage = Number(process.argv[3]);
const splitByPages = Number(process.argv[4]);
if (!path || !linesPerPage || !splitByPages) {
console.log(
'Add the file path, lines per page and split by pages numbers, please.');
process.exit();
}
/******************************************************************************/
const fs = require('fs');
const encoding = 'utf8'; //ascii utf8 utf16le
const rl = require('readline').createInterface({
input: fs.createReadStream(path, encoding),
terminal: false,
historySize: 0
});
let outFile;
let lines = 0;
let page = 0;
/******************************************************************************/
newPart(page + 1);
/******************************************************************************/
rl.on('line', line => {
fs.writeSync(outFile, `${line}\n`, null, encoding);
lines++;
if (lines === linesPerPage) {
page++;
lines = 0;
if (!(page % splitByPages)) {
newPart(page + 1);
}
}
}).on('close', () => {
fs.closeSync(outFile);
});
/******************************************************************************/
function newPart(page) {
if(outFile) {
fs.closeSync(outFile);
}
outFile = fs.openSync(path.replace(/(\.[^.]+)?$/, `.${page}$1`), 'w');
if (page !== 1) fs.writeSync(outFile, '\uFEFF', null, encoding);
console.log(page);
}
/******************************************************************************/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment