Monday 15 October 2018

node.js: fs: readdir(path[, options], callback): list files asynchronously

fs.readdir(path[, options], callback)
This method read the contents of a directory asynchronously. Below table summarizes the arguments of readdir method.

Argument
Type
Description
path
string or Buffer or URL
Absolute path of the file
options
string or Object
Below table summarizes different options.
Option
Type
Description
encoding
string
Use this encoding scheme, while returning file names. Default value is utf8.

If the encoding is set to 'buffer', the filenames returned will be passed as Buffer objects.
callback
Function
This function executes when the readdir executes successfully.

Below table summarizes the arguments of callback function.

Option
Type
Description
err
Error
Error object is null on successful scenario. On failure case it represents  error stack trace.
files
string[] or Buffer[]
Represents an array of the names of the files in the directory excluding '.' and '..'.

Find the below working example.

HelloWorld.js
var fs = require('fs');

var path = 'C:\\Users\\Public\\demo';

fs.readdir(path, (error, fileNames) => {
    if (error) {
        console.log('Error occured while read the files');
        return;
    }
    console.log(fileNames);
});

console.log('Done.......')



Previous                                                 Next                                                 Home

No comments:

Post a Comment