Use nodejs to build a static file server on Windows. Even if you don’t have any basic foundation, you can learn to build a nodejs static file server. This article introduces it in detail and is very suitable for friends who have no basic foundation to learn.
First install nodejs:
• Create a new node folder
•Download node.exe to this folder
•Download npm and unzip to the folder
•Now the node folder is like this
• Add this directory to the path environment variable
•Execute on the command line
node -vnpm -v
If you get the version number, it means that the nodejs installation is completed
•Execute on the command line
npm config set registry https://registry.npm.taobao.org
In the future, the nodejs module will be downloaded from Taobao's npm image.
• If you want to publish your own module to npm, you must first switch the npm registry back
npm config set registry https://registry.npmjs.org
Next, build a static file server
• Create a folder server, a folder root, the server is the server's js code, root is the root directory
• Create a js file 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));//The actual path of the request getPromise(function (resolve, reject) {fs.exists(realPath, function (isExists) {//Judge whether the path exists 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) {//Judge whether the path is a file or a folder if (err) {reject(err);} else {resolve(stat);}})}).then(function (stat) {if (stat.isFile()) {//The path corresponds to a file resFile(response, realPath);} else if (stat.isDirectory()) {//The path corresponds to a folder var defaultIndexPath = path.resolve(realPath, 'index.html');return getPromise(function (resolve, reject) {fs.exists(defaultIndexPath, function (isExists) {if (isExists) {//If there is index.htmlresolve(true);} else {//There is no index.html in the folder, then the content list of the folder is displayed 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><a href="${item}">${item}</a></li>`);} else if (stat.isDirectory()) {resolve(`<li><a href="${item}/">${item}</a></li>`);} else {resolve('');}})}));});Promise.all(pmlist).then(function (linkList) {var links = '<ul>';links += '<li><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 {//Neither a file nor folder 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) {//Output a file 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);}• Press and hold the shift button in the server folder, right-click the blank area in the folder, click here to open the command window, and execute the command
node index.js
The above is the simple method of using nodejs to build a static file server on Windows that the editor introduced to you. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!