traversdir
v1.0.0
Published
recursively walks the folder/file structure, starting with a given path, and returns the information as an object.
Downloads
6
Maintainers
Readme
##Traversdir
Installation
First, install it from npm:
npm install traversdir
Then, require it as a node.js module:
const traversdir = require('traversdir');
###Usage
Provide an absolute path, of the directory that you want to scan, to the traverse()
function.
It will return an object, that has the following properties, for each directory node:
_path
- a path relative to the starting point of traversal_files
- an array containing names of all the files in the given folder_dirs
- an array containing names of all the directories in the given folder- it will also have properties named exactly same, as the names of all the directories. Each of those properties will be the next traversal step (an object) with their own
_path
,_files
,dirs
.
//create a string with an absolute path to the dir you want to work on
var test_path = path.join(path.dirname(__dirname),"your_path");
//traverse all the files and directories
//starting with the given path
//and return an object with a result
var dir_object = traversdir(test_path);
console.log( dir_object );
###Example
Imagine that you have a following file/directory structure:
folder
+── app.js
+── bg.jpg
+── first
│ +── a
│ +── component2.js
│ +── component.js
+── index.html
+── second
│ +── a
│ +── b
│ │ +── b.jade
│ +── menu1.jade
│ +── menu2.jade
│ +── navbar.jade
+── third
+── 01.jpg
+── 02.jpg
+── 03.jpg
You can provide the path of the 'folder' to the traversdir()
function, like so:
var your_path = path.join(path.dirname(__dirname), "folder");
var folder = traversdir(your_path);
console.log( folder );
And it will return the following object:
{
_path: '/',
_files: ['app.js', 'bg.jpg', 'index.html'],
_dirs: ['first', 'second', 'third'],
first: {
_path: '/first',
_files: ['component.js', 'component2.js'],
_dirs: ['a'],
a: {
_path: '/first/a',
_files: [],
_dirs: []
}
},
second: {
_path: '/second',
_files: ['menu1.jade', 'menu2.jade', 'navbar.jade'],
_dirs: ['a', 'b'],
a: {
_path: '/second/a',
_files: [],
_dirs: []
},
b: {
_path: '/second/b',
_files: 'b.jade',
_dirs: []
}
},
third: {
_path: '/third',
_files: ['01.jpg', '02.jpg', '03.jpg'],
_dirs: []
}
}
Now you can access arrays of names of the files and directories on any node, as well as the relative paths to it, like so:
//for the ./folder/second path
console.log(folder.second._files) // ['menu1.jade', 'menu2.jade', 'navbar.jade']
console.log(folder.second._dirs) // ['a', 'b']
console.log(folder.second._path) // '/second'