1. 程式人生 > >node 實現靜態服務server.js

node 實現靜態服務server.js

node 實現靜態服務server.js

將下面程式碼儲存為server.js,然後放到再需要靜態訪問的目錄下,執行命令:node server.js,
即可通過url 地址訪問對應檔案。(預設埠:8888)

// 引入相應模組
var http = require('http'),
	 url = require('url'),
	path = require('path'),
	  fs = require('fs');
	  
var port = process.argv[2] || 8888;

var types = {
	'mp3': 'audio/mpeg',
	'html'
: 'text/html', 'js': 'application/javascript' }, site = 'http://localhost:' + port; http.createServer(function (request, response) { var uri = url.parse(request.url).pathname, filename = path.join(__dirname, uri); fs.exists(filename, function (exists) { if (!exists) { response.
writeHead(404, {'Content-Type': 'text/plain', 'X-my-param':'zcyue'}); response.write('404 Not Found\n'); response.end(); return; } if(!fs.lstatSync(filename).isDirectory()) { var type = filename.split('.'); type = type[type.length - 1
]; response.writeHead(200, { 'Content-Type': types[type] + '; charset=utf-8' }); fs.createReadStream(filename).pipe(response); } else { response.writeHead(301, {'Location': site + '/www/app.html' }); response.end(); } }); }).listen(parseInt(port, 10)); console.log('Static file server running at\n => ' + site + '/\nCTRL + C to shutdown');

至此,結束。