0

I need to be able to loop through an array of file paths and filter out files that do not contain a particular string within them. The target array returns an empty array, but instead I want the target array to include the list of files that do not contain the string, with results parsed to remove a substring up to the last instance of the delimiter.

const fs = require('fs')

const fileList = ['/L1/L2/file1', '/L1/L2/file2', '/L1/L2/file3', '/L1/L2/file4']
const filterText = 'filter files that contain me'
let targetArray = []

async function parseIncompleteDocumentation() {
  try {
    const delimiter = '/'
    for (let componentFile of coveredComponentsDirectoryList)
      return new Promise((resolve, reject) => {
        fs.readFile(componentFile, 'utf8', function(err, content) {
          if (err) {
            reject(err)
          } else if (!content.includes(incompleteDocumentationFilter)) {
            resolve(
              existingIncompleteComponentDocumentationList.push(
                componentFile.substring(
                  componentFile.lastIndexOf(delimiter) + 1,
                  componentFile.length
                )
              )
            )
          }
        })
      }
    )
  } catch (err) {
    return console.log('error message', err) // eslint-disable-line no-console
  }
}

const finalArray = await parseFiles()
console.log(finalArray) // returns empty array

If file1 and file3 contain filterText, desired output would be ['file2', 'file4']

3
  • 1
    Promises and forEach don't mix. Try replacing with a simple for of. Commented Jul 23, 2020 at 15:51
  • 1
    You have a bug, foreach wont stop once you resolve. Commented Jul 23, 2020 at 15:52
  • @Keith I updated my question with your suggestion, but it's still printing an empty array. Any advice? Commented Jul 23, 2020 at 20:49

1 Answer 1

1

There are few options:

  1. Use async/await inside for...of loop.

    for (let file of fileList) {
    
      await new Promise((resolve, reject) => {
          fs.readFile(file, 'utf8', (err, content) => {
    
             if (err)
               return reject(err);
    
             //....
             resolve()
          })
      })
    }
    
  2. Use readFileSync

    fileList.forEach(file => {
    
       try{
          let content  = fs.readFileSync(file, 'utf8');
          //...
       }
       catch(e) {
          //....
       }
    })    
    
Sign up to request clarification or add additional context in comments.

1 Comment

Option 2, of course could cause issues. Current versions of node also come with promisified versions of readFile etc to avoid the Promise constructor. nodejs.org/dist/latest-v10.x/docs/api/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.