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)
- How can I write a file to the directory with all the files read?
- 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');
});