Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@hasegawayosuke
Last active November 16, 2015 07:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hasegawayosuke/41811c020ba0c4d7321c to your computer and use it in GitHub Desktop.
Save hasegawayosuke/41811c020ba0c4d7321c to your computer and use it in GitHub Desktop.
tiny httpd with auto-reload
if(""==0) {/*
@echo off
title httpd %CD%
:loop
node "%~f0" %*
if %ERRORLEVEL% EQU 35 GOTO loop
goto :eof
*/
}
"use strict";
var http = require('http');
var url = require( 'url' );
var fs = require( 'fs' );
var mimeTypes = {
txt : "text/plain",
pdf : "application/pdf",
html : "text/html",
htm : "text/html",
js : "application/javascript",
css : "text/css",
};
(function(){
fs.watchFile( __filename, { persistent : true }, function( curr, prev ){
process.exit( 35 );
} );
http.createServer(function (req, res) {
var location = url.parse( req.url );
console.log( (new Date()), location.href );
var pathname = location.pathname || "/";
var handleStatic = function( filename, res ){
var stream;
var ext;
var type;
if( ( filename.indexOf( "../" ) !== -1 ) || ( filename.indexOf( "..\\" ) !== -1 ) ){
res.writeHead( 400, { "Content-Type" : "text/html" } );
res.end( "<html><body>400 Bad Request</body></html>" );
return;
}
ext = ( /\.([^\.]+)$/.exec( filename )||[])[ 1 ];
if( ext ) type = mimeTypes[ ext ];
if( !type ) type = "application/octet-stream";
stream = fs.createReadStream( filename );
stream.on( "data", function( data ){
if( !res.headersSent ){
res.writeHead( 200, { "Content-Type" : type } );
}
res.write( data );
} );
stream.on( "end", function(){
res.end();
} );
stream.on( "error", function( e ){
if( e.code === "ENOENT" ){
res.writeHead( 404, { "Content-Type" : "text/html" } );
res.end( "<html><body>404 Not Found</body></html>" );
}else{
console.error( e );
if( !res.headersSent ){
res.writeHead( 500, { "Content-Type" : "text/plain" } );
}
res.end();
}
} );
};
if( pathname.match( /\/$/ ) ){
handleStatic( "." + pathname + "index.html", res );
}else if( pathname === "/redir" ){
// test code 1
res.writeHead( 302, { "Location" : "http://utf-8.jp/" } );
res.end();
}else if( pathname === "/edge" ){
// test code 2
res.writeHead( 200, { "Content-Type" : "text/html" } );
var s = '<html><body><a href="microsoft-edge:http://www.google.com/">aa</a><br>' +
'<a href="ms-cortana://">aa</a><br>"'+
'<a href="microsoft-edge:javascript:">aa</a><br>"';
res.end( s );
}else{
// static file
handleStatic( "." + pathname, res );
}
}).listen(80);
console.log( "Running server on port 80" );
})()
@hasegawayosuke
Copy link
Author

backspace(0x08) x16 in first line.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment