placeholder
placeholder

Reputation: 75

Node.js Comparing filenames in directory with filenames in text file

I have a txt file with list of filenames that should be in a directory. I have also a directory, in which I have many files. I need to delete all files from the directory, which filenames are not present in the txt file.

Let me provide a quick example to clarify my problem: We have file.txt which contains the following: "a.pbo b.txt c.gif" We have also a folder (directory) which contains such files: a.pbo, b.txt, c.gif, d.png As "d.png" is not present in file.txt, we need to delete it from the folder (directory).

I was thinking about using for loop, going through all files in the folder and each time opening the file and searching for the filename, but i'm completely new to node.js and electron framework and don't know how to do that.

Edit: Link to exact content of my file.txt and it's structure in comment.

Upvotes: 0

Views: 535

Answers (1)

boehm_s
boehm_s

Reputation: 5544

You need fs to perform operations on your system.
The split method allows you to turn your filenames into an array of filenames - since they seem to be separated by spaces.
Then, filter the filenames that aren't ( = !includes) in your list and remove them (fs.unlinkSync)

Here is what you could do :

const fs = require('fs');

const FILENAME = 'youfilename.txt';
const DIRECTORY = '/path/to/yourDirectory';
const SEPARATOR = " ";

const content = fs.readFileSync(FILENAME, 'utf8');
const fileList = content.split(SEPARATOR);
const filesInDir = fs.readdirSync(DIRECTORY);
const filesToRemove = filesInDir.filter(fileName => !fileList.includes(fileName))

filesToRemove.forEach(fileName => fs.unlinkSync(fileName));

Note that I use Sync operations because it's easier, otherwise you would have to deal with Promises or callbacks. Sync operations are slower by nature, but I think that in your use case it won't impact the performances of your program.

EDIT

I'll let the code above as it is and give you a piece of code that can turn your string into an array of array, then just adjust the code.

var str = `Array
(
    [0] => .
    [1] => ..
    [2] => a.png
    [3] => logo.paa
    [4] => b.gif
    [5] => d.dll
    [6] => e.dll
    [7] => f.png
)
Array
(
    [0] => .
    [1] => ..
    [2] => text.txt
)
`;

var newStr = str
  .split('\n')
  .filter(s => s.trim() !== "Array" && s.trim() !== "(")
  .join("\n")
  .split(")")
  .map(s => s
    .split("\n")
    .map(s => s
      .trim()
      .split("=> ")[1]
    )
    .filter(n => n)
  )
  .filter(arr => arr.length > 0);

console.log(newStr);

It would have been cleaner with regexp, but I like String and Array methods, I find it more understandable.

Hope it helps,
best regards

Upvotes: 1

Related Questions