Node.js - Sync directory search using fs.readdirSync
Introduction
This tutorial introduce the synchronous recursive directory search using Node.js fs.readdirSync
.
Solution
Parallel loop to sync directory search
The following example shows a synchronous way to search file with js extension.
Filesystem = require('fs');
var findFile, jsFiles, rootDir;
jsFiles = [];
findFile = function(dir)
{
Filesystem.readdirSync(dir).forEach(function(file) {
var stat;
stat = Filesystem.statSync("" + dir + "/" + file);
if (stat.isDirectory())
{
return findFile("" + dir + "/" + file);
}
else if (file.split('.').pop() === 'js')
{
return jsFiles.push("" + dir + "/" + file);
}
});
};
// test it out on home directory
findFile(process.env.HOME);
console.log(jsFiles);
Above example written in CoffeeScript
jsFiles = []
# Method to find js file recursively
findFile = (dir) ->
Filesystem.readdirSync(dir).forEach (file) ->
stat = Filesystem.statSync "/"
if stat.isDirectory() then findFile("/")
else if file.split('.').pop() is 'js'
jsFiles.push "/"
# test it out on home directory
findFile process.env.HOME
References & Resources
- N/A
Latest Post
- Dependency injection
- Directives and Pipes
- Data binding
- HTTP Get vs. Post
- Node.js is everywhere
- MongoDB root user
- Combine JavaScript and CSS
- Inline Small JavaScript and CSS
- Minify JavaScript and CSS
- Defer Parsing of JavaScript
- Prefer Async Script Loading
- Components, Bootstrap and DOM
- What is HEAD in git?
- Show the changes in Git.
- What is AngularJS 2?
- Confidence Interval for a Population Mean
- Accuracy vs. Precision
- Sampling Distribution
- Working with the Normal Distribution
- Standardized score - Z score
- Percentile
- Evaluating the Normal Distribution
- What is Nodejs? Advantages and disadvantage?
- How do I debug Nodejs applications?
- Sync directory search using fs.readdirSync