Advertisement
Guest User

Untitled

a guest
Dec 7th, 2016
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. const fs = require('fs');
  2. const readline = require('readline');
  3. const minimist = require('./minimist.js');
  4.  
  5. const opts = minimist(process.argv.slice(2));
  6. const args = opts._;
  7.  
  8. if (args.length !== 1) {
  9. console.error('Invalid number of arguments received.');
  10. process.exit(1);
  11. }
  12.  
  13. const spacesString = buildSpaces(opts.n || 2);
  14. const inputFile = getInputFile(args[0]);
  15. const outputFile = getOutputFile(inputFile);
  16.  
  17. const fileReader = readline.createInterface({
  18. input: fs.createReadStream(inputFile.path, {encoding: 'utf8'}),
  19. });
  20. const outputFD = fs.openSync(outputFile.path, 'w');
  21.  
  22. let totalTabChars = 0;
  23. let start = null;
  24.  
  25. fileReader.on('line', line => {
  26. let matches = line.match(/\t/g);
  27.  
  28. if (matches) {
  29. totalTabChars += matches.length;
  30. }
  31.  
  32. fs.writeSync(outputFD, line.replace(/\t/g, spacesString) + '\n', 'utf8');
  33. });
  34.  
  35. fileReader.on('close', () => {
  36. let end = Date.now();
  37. fs.closeSync(outputFD);
  38.  
  39. console.log('\nFile processing done.');
  40. console.log(`Time elapsed : ${end-start}ms`);
  41. console.log(`Tabs replaced : ${totalTabChars}`);
  42. });
  43.  
  44. start = Date.now();
  45.  
  46. /********** functions **********/
  47.  
  48. function buildSpaces(numSpaces) {
  49. let str = '';
  50.  
  51. for (let i = 0; i < numSpaces; i++) {
  52. str += ' ';
  53. }
  54.  
  55. return str;
  56. }
  57.  
  58. function getInputFile(arg) {
  59. const path = require('path');
  60. const file = {};
  61.  
  62. file.dir = path.join(process.cwd(), path.dirname(arg));
  63. file.ext = path.extname(arg);
  64. file.basename = path.basename(arg, file.ext);
  65. file.name = path.basename(arg);
  66. file.path = path.join(file.dir, file.name);
  67.  
  68. return file;
  69. }
  70.  
  71. function getOutputFile(inputFile) {
  72. const path = require('path');
  73. const file = {};
  74.  
  75. file.dir = inputFile.dir;
  76. file.ext = inputFile.ext;
  77. file.basename = inputFile.basename + '-spaces';
  78. file.name = file.basename + inputFile.ext;
  79. file.path = path.join(file.dir, file.name);
  80.  
  81. return file;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement