Node.js file navigation with closures and generators

node v8.17.0
version: 1.0.1
endpointsharetweet
This is a playground to test JavaScript. It runs a completely standard copy of Node.js on a virtual server created just for you. Every one of npm’s 300,000+ packages are pre-installed, so try it out:
const path = require('path'); const fs = require('fs'); // From http://sagegerard.com/slick-node-js-file-navigation/ function mount(home) { function vantage(...args) { return path.resolve(home, ...args); } vantage.cd = function (...args) { return mount(vantage(...args)); }; vantage.walk = function* () { for (const basename of fs.readdirSync(home)) { const abspath = path.join(home, basename); const stat = fs.statSync(abspath); const nest = yield [abspath, basename, stat]; if (stat.isDirectory() && (nest === undefined || nest === true)) { yield* vantage.cd(abspath).walk(); } } }; vantage.ls = function* () { const it = vantage.walk(); let { done, value } = it.next(false); while (!done) { yield value; ({ done, value } = it.next(false)); } }; return vantage; }
const root = mount('/'); console.log(Array.from(root.ls()).map(([,bn]) => bn))
Loading…

no comments

    sign in to comment