0

I have two folders, input and output folder with many text files in the below format. How do I read all the files from the input folder,run the regex and write all the updated files to another output folder?I am using nodejs.

Input: $.Carpool[0].NoofSeats], [$.Carpool[1].NoofSeats]

So after replace with regex the updated text file should be:

Regex: str = str.replace(/\.[A-Z]/g, (m0) => m0.toLowerCase());

Output: [$.carpool[0].noOfSeats], [$.carpool[1].noOfSeats]

So far I got to reading files from the directory:

const fs= require("fs");

let directory = "Input" // Desktop/Input
let files = fs.readdirSync(directory)
console.log(files);
Eva
  • 109
  • 9

1 Answers1

0

You want to loop through the files, assuming if the contents are a text file in UTF-8 format here is an example.

You use fs.readFile to read a specific file after listing directory. Then use fs.writeFile to write a new file with contents.

I use /directory/${f} for the new file directory path and ${f} for filename that was opened.

const fs = require("fs");
// Directory
let directory = "/";
// Files
let files = fs.readdirSync(directory);
// Loop through the files
files.forEach(f => {
    // Read the contents in UTF-8 format
    fs.readFile(f, 'utf8', function(err, contents) {
        if (err) { console.log(err); }
        // Output Contents
        console.log(contents);
        // Perform regex here
        contents = contents.replace(/\.[A-Z]/g, (m0) => m0.toLowerCase());
        // Write new file to path /new, with contents
        fs.writeFile(`/directory/${f}`, contents, function(err) {
            if (err) {
                // Error writing
                return console.log(err);
            }
            console.log("The file was saved!");
        });
    });
});
ABC
  • 2,068
  • 1
  • 10
  • 21
  • I have two folders named "Input" and "Output" on my Desktop. So do I add the whole path like C:\Users\Eva\Desktop\Input? Also, I am getting the error: contents = contents.replace(/\.[A-Z]/g, (m0) => m0.toLowerCase()); ^ TypeError: Cannot read property 'replace' of undefined at ReadFileContext.callback – Eva Jun 16 '19 at 03:56
  • Also, when I am writing files, if I have four .txt files in input folder with those records(any number) I would want four files to be generated in the output folder with the updated data. – Eva Jun 16 '19 at 03:59