Advertisement
Guest User

formatter.js

a guest
May 17th, 2015
344
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // This code assumes all files are in the /input folder.
  2. // The formatted files will be in the /output folder
  3. // Take care of these two things:
  4. // 1) The code loads each file in memory before transforming it - be sure you've got enough RAM to run it
  5. // 2) The code may break some code if it fails to format it
  6.  
  7. var INPUT_DIR = "input";
  8. var OUTPUT_DIR = "output";
  9.  
  10. var fs = require("fs");
  11. fs.readdir(INPUT_DIR, function (err, fileNames) {
  12.     if (err) {
  13.         console.log("There is no directory called " + INPUT_DIR);
  14.         throw err;
  15.     }
  16.    
  17.     fileNames.forEach(function (fileName, index) {
  18.         var fullPath = INPUT_DIR + "/" + fileName;
  19.         fs.readFile(fullPath, "utf-8", function (err, fileContents) {
  20.             if (err) {
  21.                 console.log("There was a trouble reading file " + fullPath);
  22.                 throw err;
  23.             }
  24.            
  25.             console.log("Processing file " + fullPath);
  26.            
  27.             // Remove many consecutive new lines and spaces
  28.             fileContents = fileContents.replace(/(\r\n\s*)+/g, "\r\n");
  29.            
  30.             var outputPath = OUTPUT_DIR + "/" + fileName;
  31.             fs.writeFile(outputPath, fileContents, function (err) {
  32.                 if (err) {
  33.                     console.log("There was a trouble writing file " + fullPath);
  34.                     throw err;
  35.                 }
  36.  
  37.                 console.log("File " + outputPath + " saved");
  38.             });
  39.         });
  40.     });
  41. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement