From time to time, I need to host some static files to do some local jobs. One possible solution is to set up the config file of the server engine (eg. apache, nginx). However, you need to restart the engine or reload the config file, and you may encounter really annoying some errors. Recently, I found node.js server function is quite useful in doing such things. You can easily set up servers on different ports and easily change the path. Here is the simple code:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25//server.js
var http = require('http');
var parse = require('url').parse;
var join = require('path').join;
var fs = require('fs');
var root = __dirname + '/public';
var server = http.createServer(function(req, res){
var url = parse(req.url);
var path = join(root, url.pathname);
var stream = fs.createReadStream(path);
stream.on('error', function(err){
res.statusCode = 500;
res.end('Internal Server Error');
});
stream.on('data', function(chunk){
res.write(chunk);
});
stream.on('end', function(){
res.end();
});
});
server.listen(3000);
Just put your files in the \public
folder and run node server.js
. All things are done! You can check them out on localhost:3000
.
A more elegant way is to utilize the pipe()
mechanism:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20//server.js
var http = require('http');
var parse = require('url').parse;
var join = require('path').join;
var fs = require('fs');
var root = __dirname + '/public';
var server = http.createServer(function(req, res){
var url = parse(req.url);
var path = join(root, url.pathname);
var stream = fs.createReadStream(path);
stream.pipe(res);
stream.on('error', function(err){
res.statusCode = 500;
res.end('Internal Server Error');
});
});
server.listen(3000);
Very easy isn’t it?