Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const fs = require('fs');
- const readline = require('readline');
- const minimist = require('./minimist.js');
- const opts = minimist(process.argv.slice(2));
- const args = opts._;
- if (args.length !== 1) {
- console.error('Invalid number of arguments received.');
- process.exit(1);
- }
- const spacesString = buildSpaces(opts.n || 2);
- const inputFile = getInputFile(args[0]);
- const outputFile = getOutputFile(inputFile);
- const fileReader = readline.createInterface({
- input: fs.createReadStream(inputFile.path, {encoding: 'utf8'}),
- });
- const outputFD = fs.openSync(outputFile.path, 'w');
- let totalTabChars = 0;
- let start = null;
- fileReader.on('line', line => {
- let matches = line.match(/\t/g);
- if (matches) {
- totalTabChars += matches.length;
- }
- fs.writeSync(outputFD, line.replace(/\t/g, spacesString) + '\n', 'utf8');
- });
- fileReader.on('close', () => {
- let end = Date.now();
- fs.closeSync(outputFD);
- console.log('\nFile processing done.');
- console.log(`Time elapsed : ${end-start}ms`);
- console.log(`Tabs replaced : ${totalTabChars}`);
- });
- start = Date.now();
- /********** functions **********/
- function buildSpaces(numSpaces) {
- let str = '';
- for (let i = 0; i < numSpaces; i++) {
- str += ' ';
- }
- return str;
- }
- function getInputFile(arg) {
- const path = require('path');
- const file = {};
- file.dir = path.join(process.cwd(), path.dirname(arg));
- file.ext = path.extname(arg);
- file.basename = path.basename(arg, file.ext);
- file.name = path.basename(arg);
- file.path = path.join(file.dir, file.name);
- return file;
- }
- function getOutputFile(inputFile) {
- const path = require('path');
- const file = {};
- file.dir = inputFile.dir;
- file.ext = inputFile.ext;
- file.basename = inputFile.basename + '-spaces';
- file.name = file.basename + inputFile.ext;
- file.path = path.join(file.dir, file.name);
- return file;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement