node.js, get file names in a directory

This program prints a list of files in a given directory, filtered by the extension of the files. The given direcory path and the file extension need to be provided as the first and second argument respectively. For example, if you provide ‘/home/data/’ as the first argument and ‘zip’ as the second argument, the program will print the name of all the zip files in /home/data/. node getFiles.js /home/data/ zip

var fs = require('fs');
var path = require('path');
var dirPath = process.argv[2];	//directory path
var fileType = '.'+process.argv[3]; //file extension
var files = [];
fs.readdir(dirPath, function(err,list){
	if(err) throw err;
	for(var i=0; i<list.length; i++)
	{
		if(path.extname(list[i])===fileType)
		{
			console.log(list[i]); //print the file
			files.push(list[i]); //store the file name into the array files
		}
	}
});

Search within Codexpedia

Custom Search

Search the entire web

Custom Search