draxt.js – NodeList/jQuery-like package for File System (node.js)
draxt
is a utility module for selecting and manipulating filesystem objects in a Node.js environment.
It uses glob patterns as its “selector engine”. draxt
also provides several DOM-like interfaces representing filesystem objects which build on promisified APIs for the fs
and fs-extra
modules.
draxt means tree in the Pahlavi language.
/app/
├── controllers/
│ └── index.js
├── public/
│ ├── script.js
│ └── style.css
└── views/
└── index.njk
// Let's use a familiar variable name!
const $ = require('draxt');
(async () => {
// Select `/app` directory contents and create a new `draxt` collection.
const $app = await $('/app/**');
$app
// Let's filter js files:
.filter(node => node.extension === 'js')
// Now we have a new `draxt` collection with 2 nodes.
.forEach(async (node, index, allNodes) => {
// `node` is instance of `File` class. Because it's a file!
console.log(node.pathName);
// → '/app/controllers/index.js' for the first node!
console.log(node instanceof $.File); // → `true`
// Let's get contents of the node. `file.read` returns a promise object.
const content = await node.read('utf8');
// Let's use some synchronous methods!
node.appendSync('\na new line!')
.chmodSync('765')
// move the file into another directory!
.appendToSync('/hell') // or `.moveToSync('/hell')`
console.log(node.pathName);
// → '/hell/index.js' for the first node in the list!
// get the parent directory of the node.
// returns a `Directory` instance with the pathName of '/hell'!
const parentNode = node.parentSync(); // or `await node.parent()`
// is the directory empty?
console.log(parentNode.isEmptySync()); // → `false`
});
})();
Key notes:
draxt
has only 2 dependencies: glob
and fs-extra
modules.draxt
uses glob
patterns to select filesystem objects.draxt
collection is an instance of a File
, Directory
, or SymbolicLink
class, which is a subclass of Node
.node.siblingsSync()
for node.siblings()
.draxt
is a simple constructor function. You can extend/overwrite its methods via its prototype
property (or its fn
alias) or by using the draxt.extend
method.const draxt = require('draxt');
// Add a method (`images`) for filtering image files.
draxt.fn.images = function() {
const imgExtensions = ['jpeg', 'jpg', 'png', 'git', ...];
return this.filter(node => {
return node.isFile() && imgExtensions.indexOf(node.extension) > -1;
});
}
Installing via npm:
$ npm i draxt
Via yarn:
$ yarn add draxt
draxt
APIs$ npm test