How to write file to every directory that is read?

Viewed 35

I have the following folder structure below and wanted to create a file in each directory indicating which files were read. After the file is created, I want to use that file as a conditional to determine if I should skip or read from that directory.

Question(s)

  1. How can I write a file to the directory with all the files read?
  2. How can I use that file in conditional logic to read or skip that file directory?

Current Folder Structure (before running nodejs)

  • sub folder 1 -- file 1 -- file 2 -- file 3
  • sub folder 2 -- file 3 -- file 4
  • sub folder 3 -- file 5 -- file 6

Desired Output (after running nodejs file)

  • sub folder 1 -- file 1 -- file 2 -- file 3 -- files-read.txt
  • sub folder 2 -- file 3 -- file 4 -- files-read.txt
  • sub folder 3 -- file 5 -- file 6 -- files-read.txt

What I have tried but got stuck

const fs = require('fs');
var targetDirectory = '../my/path/to/target';
var filesRead = [];

fs.readdir(targetDirectory, function (err, files) {

  if(err) return console.log('error: ' + err);

  files.forEach(function(file) {
   // HELP - how do i not read if files-read.txt already exists in directory?
   filesRead.push(file);
  });

});

var fileName = 'files-read.txt';

fs.writeFile(fileName, filesRead, function (err) {
  if(err) return console.log('error: ' + err);
  /// help -- how do i only write if files-read.text doesn't exist?
  console.log('finished writing');
});
1 Answers

You need to cycle through the sub folders. In your case it would look like this:

const fs = require('fs');
var targetDirectory = __dirname + '/target';
var filesRead = [];
var fileName = 'files-read.txt';

const { readdirSync } = fs;

const getDirectories = (source) =>
  readdirSync(source, { withFileTypes: true })
    .filter((dirent) => dirent.isDirectory())
    .map((dirent) => dirent.name);

const directories = getDirectories(targetDirectory);

directories
  .map((dir) =>
    fs.readdir(targetDirectory + '/' + dir, function (err, files) {
      if (err) return console.log('error: ' + err);
      if(files.includes(fileName)) {
        // Check to see if the file already exists
        return null
      }
      fs.writeFile(fileName, filesRead, function (err) {
        if (err) return console.log('error: ' + err);
        console.log(files); // or do what ever you want here
        console.log('finished writing');
      });
    })
  );
Related