Home > Software design >  Asynchronous method in node js is not working
Asynchronous method in node js is not working

Time:03-26

This is the most simple async code you can ever imagine but I don't know why I can't figure out why it is not working. This is my code:

const fs = require('fs');
fs.readdirSync('./', function (err, files) {
if (err)
  console.log('Error!!', err);
else
  console.log("Result!!",files);
});

This is my terminal:

% node main.js

%

Terminal image

Literally nothing happens...

CodePudding user response:

"readdirSync" is a synchronized function and you are using it as async style, use "readdir" instead or just get result from function return https://www.geeksforgeeks.org/node-js-fs-readdirsync-method/

CodePudding user response:

Use fs.readdir() or fs.readdirSync() to read the contents of a directory.

This piece of code reads the content of a folder, both files and subfolders, and returns their relative path:

const fs = require('fs')

const folderPath = '/Users/joe'

fs.readdirSync(folderPath)

  • Related