步驟:
一、安裝node;
二、新建一個文件夾目錄(根目錄),里面再新建一個server.js文件;
三、打開命令行界面,進入文件夾目錄然后輸入命令node server.js;
四、然后就可以在瀏覽器上通過localhost:8080進行文件的訪問了。例如:根目錄下有個index.html,那么訪問地址是:localhost:8080/index.html;
server.js配置文件如下:
'use strict';
var
fs = require('fs'),
url = require('url'),
path = require('path'),
http = require('http');
// 從命令行參數獲取root目錄,默認是當前目錄:
//process代表當前Node.js進程
var root = path.resolve(process.argv[2] || '.');// 創建服務器:
var server = http.createServer(function (request, response) {
// 獲得URL的path,類似 '/css/bootstrap.css':
var pathname = url.parse(request.url).pathname;
// 獲得對應的本地文件路徑,類似 '/srv/www/css/bootstrap.css':
var filepath = path.join(root, pathname);
// 獲取文件狀態:
fs.stat(filepath, function (err, stats) {
if (!err && stats.isFile()) {
// 沒有出錯並且文件存在:
console.log('200 ' + request.url);
// 發送200響應:
response.writeHead(200);
// 將文件流導向response:
fs.createReadStream(filepath).pipe(response);
} else {
// 出錯了或者文件不存在:
console.log('404 ' + request.url);
// 發送404響應:
response.writeHead(404);
response.end('404 Not Found');
}
});
});
server.listen(8080);
console.log('Server is running at http://127.0.0.1:8080/');