在windows上用nodejs搭建靜態檔案伺服器的簡單方法_node.js

來源:互聯網
上載者:User

在windows上用nodejs搭建一個靜態檔案伺服器,即使你一點基礎沒有也能學會nodejs靜態檔案伺服器的搭建,本文介紹的非常詳細,很適合零基礎入門的朋友學習。

首先安裝nodejs:

•建立一個node檔案夾

•下載node.exe到該檔案夾

•下載npm然後解壓到該檔案夾

•現在node檔案夾是這樣的

•把該目錄加入到path環境變數

•在命令列執行

node -vnpm -v

如果得到了版本號碼則表示nodejs安裝完成

•在命令列中執行

npm config set registry https://registry.npm.taobao.org

以後安裝nodejs模組 都會從淘寶的npm鏡像中下載

•如果想要發布自己的模組到npm要先把npm的registry切換回來

npm config set registry https://registry.npmjs.org

接下來搭建靜態檔案伺服器

•建立一個檔案夾server,一個檔案夾root,server內是伺服器的js代碼,root是根目錄

•server檔案夾裡面建立js檔案 index.js mime.js server.js

•index.js

var server = require('./server.js');var rootpath = 'root';var sv = server.create({port: '9587',host: '127.0.0.1',root: rootpath}); •mime.js var types = {"css": "text/css","less": "text/css","gif": "image/gif","html": "text/html","ejs": "text/html","ico": "image/x-icon","jpeg": "image/jpeg","jpg": "image/jpeg","js": "text/javascript","json": "application/json","pdf": "application/pdf","png": "image/png","svg": "image/svg+xml","swf": "application/x-shockwave-flash","tiff": "image/tiff","txt": "text/plain","wav": "audio/x-wav","wma": "audio/x-ms-wma","wmv": "video/x-ms-wmv","xml": "text/xml","default": "text/plain"};module.exports = function (ext) {return types[ext] || 'text/plain'}

•server.js

var http = require('http');var path = require('path');var fs = require('fs');var url = require("url");var mime = require('./mime.js');function getPromise(cbk) {return (new Promise(cbk));}exports.create = function (opts) {var root = opts.root;var sv = http.createServer();function request(request, response) {var pathname = decodeURIComponent(url.parse(request.url).pathname);var realPath = path.resolve(path.join(root, pathname));//請求的實際路徑getPromise(function (resolve, reject) {fs.exists(realPath, function (isExists) {//判斷路徑是否存在isExists ? resolve() : reject();});}).catch(function () {resWrite(response, '404', 'html', '<h1>404</h1>file or dir : <h3>' + pathname + '</h3>not found');}).then(function () {return getPromise(function (resolve, reject) {fs.stat(realPath, function (err, stat) {//判斷路徑是檔案還是檔案夾if (err) {reject(err);} else {resolve(stat);}})}).then(function (stat) {if (stat.isFile()) {//路徑對應的是一個檔案resFile(response, realPath);} else if (stat.isDirectory()) {//路徑對應的是一個檔案夾var defaultIndexPath = path.resolve(realPath, 'index.html');return getPromise(function (resolve, reject) {fs.exists(defaultIndexPath, function (isExists) {if (isExists) {//如果該檔案夾內有index.htmlresolve(true);} else {//該檔案夾內沒有index.html 則 顯示該檔案夾的內容列表resolve(false);}})}).then(function (isExistsIndex) {if (isExistsIndex) {resFile(response, defaultIndexPath);} else {return getPromise(function (resolve, reject) {fs.readdir(realPath, function (err, list) {if (err) {reject(err);} else {resolve(list);}})}).then(function (list) {var pmlist = list.map(function (item) {return (new Promise(function (resolve, reject) {fs.stat(path.resolve(realPath, item), function (err, stat) {if (err) {console.error(err);resolve('');} else if (stat.isFile()) {resolve(`<li class="file"><a href="${item}">${item}</a></li>`);} else if (stat.isDirectory()) {resolve(`<li class="dir"><a href="${item}/">${item}</a></li>`);} else {resolve('');}})}));});Promise.all(pmlist).then(function (linkList) {var links = '<ul>';links += '<li class="dir"><a href="../">../</a></li>';links += linkList.join('');links += '</ul>';var dirPage = `<!doctype html><html><head><meta charset="utf-8"/><style>a{color:blue;text-decoration: none;}.dir a{color:orange}</style></head><body>${links}</body></html>`;resWrite(response, '200', 'html', dirPage);});}).catch(function (err) {resWrite(response, '500', 'default', err.toString());})}})} else {//既不是檔案也不是檔案夾resWrite(response, '404', 'html', '<h1>404</h1>file or dir : <h3>' + pathname + '</h3>not found');}}).catch(function (err) {resWrite(response, '500', 'default', err.toString());})})}sv.on('request', request);sv.listen(opts.port, opts.host);return sv;};function resFile(response, realPath) {//輸出一個檔案fs.readFile(realPath, function (err, data) {if (err) {resWrite(response, '500', 'default', err.toString());} else {var ext = path.extname(realPath).toLocaleLowerCase();ext = (ext ? ext.slice(1) : 'unknown');resWrite(response, '200', ext, data);}});}function resWrite(response, statusCode, mimeKey, data) {response.writeHead(statusCode, {'Content-Type': mime(mimeKey)});response.end(data);}

•在server檔案夾內按住shift按鈕,滑鼠右鍵點擊檔案夾內空白地區,點擊在此處開啟命令視窗,執行命令

node index.js

以上所述是小編給大家介紹的在windows上用nodejs搭建靜態檔案伺服器的簡單方法,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對雲棲社區網站的支援!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.