简体   繁体   中英

Node JS readdir callback never called

I want to read all files from a directory using fs.readdir. Here is the simplified code:

var updateFeaturesFromDir = async function(dir, recurse, logString, addedString, callback){
    console.log("hello"); //This is printed
    fs.readdir('.', (err, files) => {
        console.log(files); // This is never reached
        if(err) {
            console.log(err);
            callback(err);
            return;
        }
    });

};

However, when running this, I only get the 'hello' printed to the console. Also, breakpoints set with vs code in the callback never trigger. I do not know why this is happening, since the code in the very same place worked yesterday and I do not know what change broke it.

I also tried it with an absolute path ( __dirname ) and it did not work.

I feel like I am missing something really obvious here but I cannot see it. Any help appreciated.

EDIT: node version: v14.16.0

here is how I get fs:

var fs = require('fs');

EDIT 2:

After fixing this issue like in the accepted answer, I also had the same issue with other callback functions. I found out what the reason was: I for some dumb reason had a blocking function in the index.js file. After removing that, everything worked fine again. I thought I would add this in case someone faced similar issues.

Please try the following ways

Example 1:

import { readdirSync } from "fs";

const updateFeaturesFromDir = async function (
  dir,
  recurse,
  logString,
  addedString,
  callback
) {
  try {
    console.log("hello");
    const filses = readdirSync('your path here');
    console.log('filses: ', filses);
  } catch (error) {
    console.log('Error: ', error);
    return error;
  }
};

Example 2:

import { readdir } from 'fs/promises';

const updateFeaturesFromDir = async function (
  dir,
  recurse,
  logString,
  addedString,
  callback
) {
  try {
    console.log("hello");
    const filses = await readdir('your path here');
    console.log('filses: ', filses);
  } catch (error) {
    console.log('Error: ', error);
    return error;
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM