在windows上用nodejs搭建一個(gè)靜態(tài)文件服務(wù)器,即使你一點(diǎn)基礎(chǔ)沒有也能學(xué)會(huì)nodejs靜態(tài)文件服務(wù)器的搭建,本文介紹的非常詳細(xì),很適合零基礎(chǔ)入門的朋友學(xué)習(xí)。
首先安裝nodejs:
•新建一個(gè)node文件夾
•下載node.exe到該文件夾
•下載npm然后解壓到該文件夾
•現(xiàn)在node文件夾是這樣的
•把該目錄加入到path環(huán)境變量
•在命令行執(zhí)行
node -vnpm -v
如果得到了版本號(hào)則表示nodejs安裝完成
•在命令行中執(zhí)行
npm config set registry https://registry.npm.taobao.org
以后安裝nodejs模塊 都會(huì)從淘寶的npm鏡像中下載
•如果想要發(fā)布自己的模塊到npm要先把npm的registry切換回來(lái)
npm config set registry https://registry.npmjs.org
接下來(lái)搭建靜態(tài)文件服務(wù)器
•創(chuàng)建一個(gè)文件夾server,一個(gè)文件夾root,server內(nèi)是服務(wù)器的js代碼,root是根目錄
•server文件夾里面創(chuàng)建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));//請(qǐng)求的實(shí)際路徑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()) {//路徑對(duì)應(yīng)的是一個(gè)文件resFile(response, realPath);} else if (stat.isDirectory()) {//路徑對(duì)應(yīng)的是一個(gè)文件夾var defaultIndexPath = path.resolve(realPath, 'index.html');return getPromise(function (resolve, reject) {fs.exists(defaultIndexPath, function (isExists) {if (isExists) {//如果該文件夾內(nèi)有index.htmlresolve(true);} else {//該文件夾內(nèi)沒有index.html 則 顯示該文件夾的內(nèi)容列表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) {//輸出一個(gè)文件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文件夾內(nèi)按住shift按鈕,鼠標(biāo)右鍵點(diǎn)擊文件夾內(nèi)空白區(qū)域,點(diǎn)擊在此處打開命令窗口,執(zhí)行命令
node index.js
以上所述是小編給大家介紹的在windows上用nodejs搭建靜態(tài)文件服務(wù)器的簡(jiǎn)單方法,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)武林網(wǎng)網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注