0

I'm trying to develop a simple app that if you pass a parameter in command line the application will search inside a directory and if the text match in some of the files the file should be save in a list, but when I put the console.log the value is not updated

here is my code:

const folder = "./movies/data";
const fs = require("fs");

var args = process.argv.slice(2);
console.log("myArgs: ", args);

var count = 0;
var list = [];

fs.readdir(folder, (err, files) => {
  files.forEach((file) => {
    fs.readFile(`movies/data/${file}`, "utf8", function (err, data) {
      if (err) console.log(err);
      if (data.includes("walt disney")) {
        count++;
        list.push(data);
        console.log("Found in: ", data);
      }
    });
  });
  console.log(`Foram encontradas ${count} ocorrências pelo termo ${args}.`);
});

any suggestions about what i'm doing wrong?

Jejun
  • 410
  • 2
  • 13
  • what console.log is not updated, you have two, one in your loop and the other outside it – proxim0 Apr 13 '21 at 16:58
  • *"but when I put the console.log the value is not updated": why would `console.log` have to *update* a value? You do `console.log(data)`, and `data` is not updated anywhere, so it is normal there is no update. – trincot Apr 13 '21 at 17:20
  • I updated my answer, have you tried it out? Consider giving some feedback, thank you! – axtck Apr 16 '21 at 07:42

1 Answers1

-1

For your program to work, you will have to add some Promise / async/await logic. On the moment you try to read from the files, the files are still undefined so the fs.readDir() function will not provide the wanted result.

This should work:

const { resolve } = require('path');
const { readdir } = require('fs').promises;
const fs = require("fs");

var args = process.argv.slice(2);
const pathToFiles = "./movies/";

async function getFiles(dir) {
  const dirents = await readdir(dir, { withFileTypes: true });
  const files = await Promise.all(dirents.map((dirent) => {
      const res = resolve(dir, dirent.name);
      return dirent.isDirectory() ? getFiles(res) : res;
  }));
  return Array.prototype.concat(...files);
}

getFiles(pathToFiles)
  .then(files => {
      console.log(files)
      files.forEach((file) => {
          fs.readFile(file, 'utf8', (err, data) => {
              if (err) console.log(err);
              if (data.includes(args)) {
                  console.log(`${args} found in ${file}.`);
              } else {
                  console.log(`${args} not found.`);
              }
          });
      })
  })
  .catch (e => console.error(e));
axtck
  • 3,707
  • 2
  • 10
  • 26