This page contains helpful Node.js scripts which may be useful for web developers. They were written from scratch and may be extended as you like. Every script is available as Gist or can be downloaded separately as single JavaScript file. Every snippet contains a comment to install the dependencies so there's no package.json. The snippet collection is an ongoing project.

AutoReload

AutoReload.js is a local web server but with an automatic browser reload functionality. It relies on common modules and watches for file changes inside a directory. It refreshes the browser window when a file was changed. You simply run it from the console to set a root directory. The root path can be set in the command prompt or as argument.

AutoReload.js

Download Gist
// npm install connect serve-static tiny-lr chokidar connect-livereload

var connect = require('connect');
var serveStatic = require('serve-static');
var http = require('http');
var path = require('path');
var tinylr = require('tiny-lr')();
var chokidar = require('chokidar');
var tinylrPort = 2000;
var httpPort = 3000;
var readline;
var app;

function createApp(watchPath) {
	app = connect();

	app.use(require('connect-livereload')({
		port: tinylrPort,
		serverPort: httpPort
	}));

	app.use(serveStatic(watchPath ? path.resolve(watchPath) : __dirname));
	
	tinylr.listen(tinylrPort);
	http.createServer(app).listen(httpPort);

	chokidar.watch(watchPath ? path.resolve(watchPath + '/' + '**') : '**', { ignored: /[\/\\]\./ }).on('change', function(filePath) {
		tinylr.changed({
			body: {
				files: [path.resolve(__dirname + '/' + filePath)]
			}
		});
	});
	
	console.log('Server running at http://localhost:' + httpPort);
}

if (process.argv[2]) {
	createApp(process.argv[2]);
} else {
	readline = require('readline').createInterface({
		input: process.stdin,
		output: process.stdout
	});

	readline.question('Enter path or leave blank >> ', function(watchPath) {
		createApp(watchPath);
		readline.close();
	});
}
+

SimpleWebServer

This snippet creates a local web server to serve static files like HTML, JS and CSS. It can be configured by setting a port and uses its working directory as root path for files and folders. You can adjust __dirname if you want to set the root path to another directory.

SimpleWebServer.js

Download Gist
// npm install connect serve-static

var connect = require('connect');
var serveStatic = require('serve-static');
var http = require('http');

var app = connect().use(serveStatic(__dirname));

http.createServer(app).listen(3000);
+