File Management

Node uses the fs library to provide rich and powerful file management functionality. First let's a directory and some files:

$ mkdir data; cd data
$ touch provinces.txt capitals.txt

Add the following text to provinces.txt

Alberta
British Columbia
Manitoba
New Brunswick
Newfoundland and Labrador
Nova Scotia
Ontario
Prince Edward Island
Quebec
Saskatchewan

Add the following to capitals.txt

Charlottetown
Edmonton
Fredericton
Halifax
Ottawa
Quebec
Regina
St. John's
Toronto
Victoria 
Winnipeg

Following code lists the files in a directory. It runs synchronously so not recommended for big files:

var fs = require("fs");
var files = fs.readdirSync("./data");
console.log(files);

Output:

[ 'capitals.txt', 'provinces.txt' ]

The following code lists files in a directory asynchronously:

var fs = require("fs");
fs.readdir('data',function(error, files) {
    if (error) {
        throw error;
    }
    console.log(files);
});

output:

[ 'capitals.txt', 'provinces.txt' ]