File Server

Published on June 2016 | Categories: Types, School Work | Downloads: 54 | Comments: 0 | Views: 765
of 2
Download PDF   Embed   Report

lets you share your files in a directory where the script is kept.

Comments

Content

var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs")
port = process.argv[2] || 8888;
http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname
, filename = path.join(process.cwd(), decodeURI(uri));
console.log(filename);
path.exists(filename, function(exists) {
if(!exists) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
return;
}
if (fs.statSync(filename).isDirectory()){
fs.readdir(filename, function (err, files) {
if (err) {
throw err;
}
response.writeHead(200, {'Content-type':'text/html'});
response.write("<HTML><HEAD><title>Directory Listing for " + uri + "</title>
</HEAD><BODY><h1>Directory Listing for " + decodeURI(uri) + "</h1>");
response.write("<ul>");
for( i in files ){
var rurl = url.parse(request.url).pathname;
var link= encodeURI(files[i])
console.log(link);
response.write('<li><a href="'+rurl +'/' +link+
'">' + files[i] + "</a></li>");
}
response.write(
"</ul>");
response.write("</BODY><
/HTML>");
response.end();
return;
});
}
fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}
response.writeHead(200);
response.write(file, "binary");
response.end();
});
});

}).listen(parseInt(port, 10));
console.log("Static file server running at\n => http://localhost:" + port + "/\
nCTRL + C to shutdown");

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close