node下載地址:http://nodejs.cn/
Node.js是一個事件驅動I/O服務端JavaScript環境,基於Google的V8引擎,V8引擎執行Javascript的速度非常快,性能非常好。
使用nodejs搭建本地服務器,類似於Apache。
操作步驟:
1、在文件夾下創建一個服務文件server.js。
2、進入server.js文件,打開命令面板,運行命令node serve.js。
若服務啓動成功,命令面本中會打印日誌“服務器開啓成功”。
在瀏覽器中,輸入localhost:8888可以成功訪問。
3、訪問文件可以在地址欄目中加入訪問的文件路徑
4、關閉服務器:ctrl + c,根據命令板提示操作即可關閉。
以下是詳細代碼
const http = require('http')
// 文件閱讀器
const fs = require('fs')
const url = require('url')
const path = require("path")
// 一、搭建、開啓服務
const server = http.createServer(function(req, res){
// req:接收客戶端傳來的數據
// res:想服務端發送的數據
// 若要訪問其他文件夾下的文件,需要修改root目錄
const root = __dirname
// const root = "E:\project\nodeServe"
// __dirname被執行文件的絕對路徑
// parse(url),url的拆解,常見方法還有host、port、pathname、path、query。
let filePath = root + url.parse(req.url).pathname
if (path.extname(filePath) == "") {
filePath += "/test.html"
}
// charAt(index)返回指定位置字符
if (filePath.charAt(filePath.length - 1) == '/') {
filePath += 'index.html'
}
fs.exists(filePath, function (exists) {
// 查看文件路勁是否存在
// exists(filePath,callBack)
if (exists) {
const contentTypeObj = {
// 根據後綴名設置content-type值
'.html': { "Content-Type": 'text/html;charset="utf-8"' },
'.js': { "Content-Type": "text/javascript" },
'.css': { "Content-Type": "text/css" },
'.gif': { "Content-Type": "image/gif" },
'.png': { "Content-Type": "image/png" },
}
const fileExtname = path.extname(filePath)
// extname()獲取文件的拓展名(後綴名)
fs.readFile(filePath, function (err, data) {
// readFile
// 一參:文件路徑
// 二參:回調函數
if (err) {
res.writeHead(404, {
'content-type': 'text/html;charset="utf-8"'
})
res.write('<div>讀取錯誤</div>')
res.end()
return
}
res.writeHead(200, contentTypeObj[path.extname(filePath)])
// writeHead
// 第一個參數是http請求碼,200爲連接成功
// 二參:連接成功後向客戶端寫入頭信息
// 把內容寫入document中
res.write(data)
// 發送信息
res.end()
})
return
}
res.writeHead(404, {
"content-Type": 'text/html;charset="utf-8"'
})
res.end("<h1>文件不存在!</h1>")
})
}).listen(8888)
// listen(要監聽的端口)
console.log('nodejs服務器已經開啓!')