Skip to content

Instantly share code, notes, and snippets.

@robotlolita
Forked from niklasfi/gist:806535
Created February 1, 2011 20:09
Show Gist options
  • Save robotlolita/806562 to your computer and use it in GitHub Desktop.
Save robotlolita/806562 to your computer and use it in GitHub Desktop.
var http = require('http');
var fs = require('fs');
var url = require('url');
var settingsPath='settings2.json';
var Server = function(path){
this.readSettings(path);
}
Server.prototype.readSettings=function(path){
fs.readFile(path, 'utf8', function(err,data){
if(err) throw err;
Server.prototype.parseSettings(data);
})
}
Server.prototype.parseSettings=function(data){
this.options=JSON.parse(data);
if(!this.options.downloadPath) throw new Error('downloadPath is not set in settings file');
if(this.options.downloadPath.substring(this.options.downloadPath.length-1,1)!='/') this.options.downloadPath+'/';
Server.prototype.findFiles();
}
Server.prototype.findFiles=function(){
var server_ref = this; // saves a reference to this
fs.readdir(this.options.downloadPath,function(err,files){
if(err) throw err;
server_ref.files={};
for(var i in files){
Server.prototype.addFile(files[i]);
}
console.log(JSON.stringify(server_ref.files));
})
}
Server.prototype.addFile= function(filename){
this.files[filename]={filename: filename, status: 'pre-stat'};
fs.stat(this.downloadPath+filename, (function(err, stats){
if(err) throw err;
this.files[filename].size=stats.size;
this.files[filename].status='ready';
}).bind(this)); // using .bind you'll be instructing the function to execute with the given `this`
}
var s=new Server(settingsPath);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment