0

I am new learner of javascript. I want to print the list of files in a directory and then print "completed" after listing all the files. Curretnly it is listing only the files in directory but not the "completed" text. I am not able to use promises properly. Can someone please help

var fs = require('fs');

f();

function f() {    
    match().then(result => console.log(result));
  } 

async function match() {
    await new Promise(resolve => {        
        return f1(resolve)
    });
    return "dir listing completed"
  }

  function f1() {
    fs.readdir("templates", (err, files) => {
        files.forEach(file => {
            console.log(file)
        })
    })   
  }
Nagesh
  • 344
  • 6
  • 16
  • 1
    You pass `resolve` in `f1(resolve)` but `f1` doesn't do anything with any arguments. – VLAZ Jan 07 '21 at 13:21
  • 1
    The question is closed so I can't post an answer, but `import { promises } from "fs"; async function match() { const files = await promises.readdir("templates"); for( let file in files){ console.log(file); } console.log("Completed");}` – Jeremy Thille Jan 07 '21 at 13:47
  • Thanks alot! @JeremyThille. The code is working fine after adding 2 lines "const fs = require('fs'); const promises = fs.promises;". But there is a warning "(node:24296) ExperimentalWarning: The fs.promises API is experimental" – Nagesh Jan 07 '21 at 14:01
  • `import { promises } from "fs"` should work just as fine. I'm using it all the time. I don't have this warning in Node 14 – Jeremy Thille Jan 07 '21 at 14:20

1 Answers1

-1
var fs = require('fs');

f1().then(()=>{
    console.log('Completed);
});

function f1() {
    return new Promise(resolve => {      
        fs.readdir("templates", (err, files) => {
            files.forEach(file => {
                console.log(file)
        });
        resolve();
    })   

  })
}
Danyal
  • 56
  • 4
  • 1
    That resolves before the asynchronous `readdir` operation has finished. – Quentin Jan 07 '21 at 13:30
  • Code is correct and working except I missed the single closing quote at the end of 'Completed', kindly mark it as correct. – Danyal Jan 07 '21 at 14:48
  • Even ignoring the type (which you could fix with an edit): It doesn't meet the requirements in the question. It is not correct. The Promise here is completely pointless. – Quentin Jan 07 '21 at 15:35