node.js實現http服務器進行訪問


步驟:
一、安裝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/');




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM