Use NodeJS para crear un servidor de archivos estático en Windows. Incluso si no tiene base básica, puede aprender a construir un servidor de archivos estático NodeJS. Este artículo lo presenta en detalle y es muy adecuado para amigos que no tienen base básica para aprender.
Primer instalación de NodeJS:
• Crear una nueva carpeta de nodo
• Descargar Node.exe a esta carpeta
• Descargue NPM y descomprima a la carpeta
• Ahora la carpeta de nodo es así
• Agregue este directorio a la variable de entorno de ruta
• Ejecutar en la línea de comando
nodo -vnpm -v
Si obtiene el número de versión, significa que la instalación de NodeJS está completa
• Ejecutar en la línea de comando
NPM Config Set Registry https://registry.npm.taobao.org
En el futuro, el módulo NodeJS se descargará de la imagen NPM de Taobao.
• Si desea publicar su propio módulo a NPM, primero debe volver a cambiar el registro de NPM
NPM Config Set Registry https://registry.npmjs.org
A continuación, cree un servidor de archivos estático
• Crear un servidor de carpeta, una raíz de carpeta, el servidor es el código JS del servidor, root es el directorio root
• Cree un archivo js index.js mime.js server.js
• index.js
var servidor = request ('./ server.js'); var rootPath = 'root'; var sv = server.create ({puerto: '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) {Tipos de retorno [ext] || 'Text/Plain'}• Server.js
var http = require ('http'); var ruta = require ('ruta'); var fs = require ('fs'); var url = require ("url"); var mime = require ('./ mime.js'); function getPromise (cbk) {return (new promise (cbk));} exports.create (opts) = http.createserver (); solicitud de función (solicitud, respuesta) {var patheName = decodeuriCoMponent (url.parse (request.url) .pathname); var realpath = path.resolve (path.join (root, pathname); // La ruta real de la solicitud getpromise (function (resuelve, rechazo) {fs.exists (realista (real) (real) (es real) {// juzga si la ruta existe isexists? {fs.stat (realPath, function (err, stat) {// juzga si la ruta es un archivo o una carpeta if (err) {rechazar (err);} else {resolve (stat);}})}). Entonces (function (stat) {if (stat.isfile ()) {// la ruta corresponde a un archivo resefile (respuesta, realpath);} if (stat.) (stat.)) {// La ruta corresponde a una carpeta var defaultIndExpath = path.resolve (realPath, 'index.html'); return getPromise (function (resolve, rechazar) {fs.Exists (defaultExcath, function (isExists) {if (isExists) {// si hay index.htmlResolve (verdadero);} carpeta, entonces la lista de contenido de la carpeta se muestra resuelve (false);}})}). entonces (function (isExistSindex) {if (isExistSindex) {resfile (respuesta, defaultExtExpath);} else {return getPromise (function (resuelve, rechazar) {fs.ReadDir (RealPath, function (err, lista) {err); {resolve (list);}})}). entonces (function (list) {var pmList = list.map (function (item) {return (new promise (function (resolve, rechazar) {fs.stat (path.resolve (realPath, item), function (err, stat) {if) {console.error (err); resolve ('');}); {resolve (`<li> <a href =" $ {item} "> $ {item} </a> </li>`);} else if (stat.isDirectory ()) {resolve (`<ri> <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 +=' </'</' </ule> ' `<! DOCTYPE HTML> <html> <HEAD> <meta charset =" utf-8 "/> <style> a {color: azul; text-decoration: none;}. dir a {color: naranja} </yle> </head> <body> $ {enlaces} </body> </html>`; reswrite (respuesta, '200', ',', '', '', ',', '', ',', ',', ',' ',' ',', ',', ',', ',' 200 ',' ',', ',' 200 ',' ',' 200 ',', ',' 200 ',', ',' 200 ',', '200', ',' 200 ',' 200 '', '', '200' ',', '200', '200' ',', '200', '200 dirPage);});});}). Catch (function (err) {Reswrite (respuesta, '500', 'default', err.toString ());})}})} else {// ni un archivo ni una carpeta reswrite (respuesta, '404', 'html', '<h1> 404 </h1> archivo o dir: <h3>' + ratero + ' + ratero +' + ' + ratero +' + ratero + ' +' + ratero + ' + ratero + +' + ratero + ' +' + ratero + ' + ratero +' + ratero + ' + ratero +' + ratero + ' + ratero + + ratero +' + ratero + ' + ratero +' + ratero + + ratero + ' + rutin '</h3> no encontrado');}}). Catch (function (err) {reswrite (respuesta, '500', 'default', err.toString ());})})})} sv.on ('solicitud', request); sv.listen (opts.port, opts.host); return sv;}; function resfile (respuesta, real, real 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, datos);}});} function reswrite (respuesta, statuscode, mimeKey, data) {Response.Writehead (StatusCode, {'Content-type': mime (mimekey)}); respuesta.end (data);}• Mantenga presionada el botón Mayús en la carpeta del servidor, haga clic con el botón derecho en el área en blanco en la carpeta, haga clic aquí para abrir la ventana de comando y ejecute el comando
nodo index.js
Lo anterior es el método simple de usar NodeJS para construir un servidor de archivos estático en Windows que el editor le presentó. Espero que sea útil para todos. Si tiene alguna pregunta, déjame un mensaje y el editor responderá a todos a tiempo. ¡Muchas gracias por su apoyo al sitio web de Wulin.com!