Skip to content

Instantly share code, notes, and snippets.

@nagarajhubli
Created December 23, 2015 11:06
Show Gist options
  • Save nagarajhubli/4cb526ba2cbb44e43eda to your computer and use it in GitHub Desktop.
Save nagarajhubli/4cb526ba2cbb44e43eda to your computer and use it in GitHub Desktop.
(function() {
'use strict';
var express = require('express');
var router = express.Router();
var fs = require('fs');
var path = require('path');
var string = require('string');
/* GET home page. */
router.get('/file-browser', function(req, res) {
res.render('index');
});
/* Serve the Tree */
router.get('/api/tree', function(req, res) {
var _p;
if (req.query.id == 1) {
_p = path.resolve(__dirname, '..', 'node_modules');
processReq(_p, res);
} else {
if (req.query.id) {
var query_id = string(req.query.id).replaceAll("______", "/").replaceAll("_____", "\\").replaceAll("------", ".").replaceAll("-----", ":");
_p = query_id.s;
processReq(_p, res);
} else {
res.json(['No valid data found']);
}
}
});
/* Serve a Resource */
router.get('/api/resource', function(req, res) {
var file_path = string(req.query.resource).replaceAll("______", "/").replaceAll("_____", "\\").replaceAll("------", ".").replaceAll("-----", ":").s;
res.send(fs.readFileSync(file_path, 'UTF-8'));
});
function processReq(_p, res) {
var resp = [];
fs.readdir(_p, function(err, list) {
for (var i = list.length - 1; i >= 0; i--) {
resp.push(processNode(_p, list[i]));
}
res.json(resp);
});
}
function processNode(_p, f) {
var s = fs.statSync(path.join(_p, f));
var location_path = string(path.join(_p, f)).replaceAll("/", "______").replaceAll("\\", "_____").replaceAll(":", "-----").replaceAll(".", "------");
return {
"id": location_path.s,
"text": f,
"icon" : s.isDirectory() ? 'jstree-custom-folder' : 'jstree-custom-file',
"state": {
"opened": false,
"disabled": false,
"selected": false
},
"li_attr": {
"base": location_path.s,
"isLeaf": !s.isDirectory()
},
"children": s.isDirectory()
};
}
module.exports = router;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment