Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS readdirSync() not executed

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.

like image 495
imeluntuk Avatar asked Feb 04 '23 17:02

imeluntuk


1 Answers

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.)

like image 76
Trott Avatar answered Feb 07 '23 08:02

Trott