在node官網 https://nodejs.org/en/ 下載最新的node并逐步安裝。
打開cmd,輸入 node -v這時成功的話會出現(xiàn)node的版本號。如下圖:
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-OszqdLok-1669876811332)(https://cdn.nlark.com/yuque/0/2022/png/26124887/1648718162240-9db94a4a-28ab-4130-b633-25aed151e06b.png#clientId=ufa998507-66b8-4&crop=0&crop=0&crop=1&crop=1&from=ui&id=ud2ea6fcb&margin=%5Bobject%20Object%5D&name=%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20220331171546.png&originHeight=269&originWidth=400&originalType=binary&ratio=1&rotation=0&showTitle=false&size=7086&status=done&style=none&taskId=u11367da5-5317-4413-b0f6-15b2742d3cc&title=)]
var url = require("url"),
fs = require("fs"),
http = require("http"),
path = require("path");
http.createServer(function (req, res) {
var pathname = __dirname + url.parse("/dist"+req.url).pathname;//資源指向dist目錄
if (path.extname(pathname) == "") {
pathname += "/";
}
if (pathname.charAt(pathname.length - 1) == "/") {
pathname += "index.html";
}
fs.exists(pathname, function (exists) {
if (exists) {
switch(path.extname(pathname)){
case ".html":
res.writeHead(200, {"Content-Type": "text/html"});
break;
case ".js":
res.writeHead(200, {"Content-Type": "text/javascript"});
break;
case ".css":
res.writeHead(200, {"Content-Type": "text/css"});
break;
case ".gif":
res.writeHead(200, {"Content-Type": "image/gif"});
break;
case ".jpg":
res.writeHead(200, {"Content-Type": "image/jpeg"});
break;
case ".png":
res.writeHead(200, {"Content-Type": "image/png"});
break;
default:
res.writeHead(200, {"Content-Type": "application/octet-stream"});
}
fs.readFile(pathname, function (err, data) {
res.end(data);
});
} else {
res.writeHead(404, {
"Content-Type": "text/html"
});
res.end("404 Not Found");
}
});
}).listen(3003);
console.log("監(jiān)聽3003端口");
1.3 運行服務現(xiàn)在我們創(chuàng)建node服務的代碼已完成,只需要運行它啦。
在當前server.js目錄下,打開cmd或者powershell,輸入node server.js
![微信圖片_20220331171848.png](/file/tupian/20221205/964c35471cc38c0563c0ad9c333c3866.jpg#clientId=ufa998507-66b8-4&crop=0&crop=0&crop=1&crop=1&from=ui&id=u50375870&margin=[object Object]&name=微信圖片_20220331171848.png&originHeight=45&originWidth=458&originalType=binary&ratio=1&rotation=0&showTitle=false&size=1420&status=done&style=none&taskId=ud61caec1-b124-49cf-a77c-83e8ff223c3&title=)
開啟服務后,我們在瀏覽器輸入: localhost:3003/index.html即可訪問。
你是否還在尋找穩(wěn)定的海外服務器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機房具備T級流量清洗系統(tǒng)配攻擊溯源,準確流量調度確保服務器高可用性,企業(yè)級服務器適合批量采購,新人活動首月15元起,快前往官網查看詳情吧