5

I'm a beginner in non-blocking environment, such NodeJS. Below is my simple code, which list all files in directory :

var readline = require('readline');
var rl = readline.createInterface(process.stdin, process.stdout);
var fs = require('fs');

var datafolder = './datafolder';
var datafoldername = 'datafolder';

rl.setPrompt('Option> ');
rl.prompt();
rl.on('line', function(line) {
    if (line === "right") rl.close();

    if (line == '1') {
        listFile();
    }

    rl.prompt();
}).on('close', function() {
    process.exit(0);
});

function listFile() {
    console.log(`File(s) on ${datafolder}`);
    fs.readdirSync(datafolder, (err, files) => {
        if (err) {
            console.log(err);
        } else {
            files.forEach(filename => {
                console.log(filename);
            });
        }
    });
}

If user press 1, it's suppose to execute method listFile and show all files inside.
My question is, why fs.readdirSync not executed? The program works if I do it with readdir(), but it'll mess the output to user.

1 Answer 1

14

You are passing a callback to fs.readdirSync() but *Sync() functions don't take callbacks. The callback is never run (because the function does not take a callback), so you see no output. But fs.readdirSync() does in fact execute.

fs.readdirSync() simply returns it's value (which may make the program easier to read, but also means the call will block, which may be OK depending on what your program does and how it is used.)

var resultsArray = fs.readdirSync(datafolder);

(You may want to wrap it in a try/catch for error handling.)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.