Skip to content

Instantly share code, notes, and snippets.

@hualro
Last active August 29, 2015 14:16
Show Gist options
  • Save hualro/b558b8b2a02ba1ed3876 to your computer and use it in GitHub Desktop.
Save hualro/b558b8b2a02ba1ed3876 to your computer and use it in GitHub Desktop.
list dir contents and return JSON with Node.js
/**
*
* Author: Hugo Alvarado
* Version 1.0
* March 01, 2015 - 7:53 PM
*/
var http = require('http');
var fs = require('fs');
var app = http.createServer(function(request, response) {
var dir = '/path/to/your/dir';
var r = [];
try {
var files = fs.readdirSync(dir);
files.forEach(function(f) {
var ff = dir + f;
var stats = fs.statSync(ff);
if (!stats.isDirectory()) {
r.push({"name":f,"path":ff});
}
});
} catch(e) {
r.push("Could not load directory");
}
response.setHeader('Content-Type', 'application/json');
response.end(JSON.stringify(r));
});
app.listen(1234);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment