Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
'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