繁体   English   中英

如何在 vanilla nodeJS 中提供静态文件

[英]How to serve static files in vanilla nodeJS

首先,我目前正在学习如何使用 vanilla nodeJS 来托管个人项目的 html 文件。 我正在使用以下代码来执行此操作。 我意识到为了用 html 显示图像,我需要公开提供这些文件; 但是,我不确定如何使用下面提供的代码执行此操作。 我感谢有关如何实现这一目标的任何反馈和贡献。

 var http = require("http"); var url = require("url"); var fs = require("fs"); var server = http.createServer(function (request, response) { var path = url.parse(request.url).pathname; switch (path) { case "/homepage.html": fs.readFile(__dirname + path, function(error, data) { if (error) { response.writeHead(404); response.write(error); response.end(); } else { response.writeHead(200, {'Content-Type':'text/html'}); response.write(data); response.end(); } }); break; case "/page1.html": fs.readFile(__dirname + path, function(error, data) { if (error) { response.writeHead(404); response.write(error); response.end(); } else { response.writeHead(200, {'Content-Type':'text/html'}); response.write(data); response.end(); } }); break; default: response.writeHead(404); response.write("Oops this doesn't exist!"); response.end(); } }); server.listen(8008); console.log("Server is running on port 8008");
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- Popper JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script> </head> <body> <div class = "row"> <div class = "col-sm-4"> <img src = "/image.jpg/" class = "img-fluid" class = "rounded-circle"> </div> <div class = "col-sm-8"> </div> </body> </html>

嘿,试试这段代码:

var http = require("http");
var url = require("url");
var fs = require("fs");

var server = http.createServer(function (request, response) {
   var path = url.parse(request.url).pathname;
   switch (path) {
      case "/homepage.html":
         fs.readFile(__dirname + path, function(error, data) {
            if (error) {
               response.writeHead(404);
               response.write(error);
               response.end();
            } else {
               response.writeHead(200, {'Content-Type':'text/html'});
               response.write(data);
               response.end();
            }
         });
         break;
      case "/page1.html":
         fs.readFile(__dirname + path, function(error, data) {
            if (error) {
               response.writeHead(404);
               response.write(error);
               response.end();
            } else {
               response.writeHead(200, {'Content-Type':'text/html'});
               response.write(data);
               response.end();
            }
         });
         break;
      default:
        //  response.writeHead(404);
        //  response.write("Oops this doesn't exist!");
        //  response.writeHead(200, {'Content-Type':'text/html'});
        //  response.write(data);
         console.log('I am here for path ', path);
         fs.readFile(__dirname + path, function(error, data) {
            if (error) {
               response.writeHead(404);
               response.write(error);
               response.end();
            } else {
               response.writeHead(200, {'Content-Type':'image/jpg'});
               response.write(data);
               response.end();
            }
         });
   }
});
server.listen(8008);

console.log("Server is running on port 8008");

因此,因为对于您的开关中没有案例的图像,使用了默认值。 我在默认情况下指定了要做什么。 如您所见,如果最终得到 100 个静态文件,则必须为每个文件指定一个大小写。 请注意,上面的示例仅适用于 jpg 图像。 这将很难维护并且不推荐,因为它会(可能)将您的静态数据与网站的逻辑混合在一起。

实现您想要的最简单方法是使用 express 模块,它已经具有此功能并且非常非常易于使用。

var express         = require('express');
var app             = express();
app.use(express.static(__dirname + '/mystaticcontent'));
app.use('/hiddenfolder', express.static(__dirname+'/mystaticcontent/'));
app.listen(8008);

对于第一个app.use(express.static(__dirname + '/mystaticcontent')); 如果你把 image.jpg 放在这个文件夹中,你可以使用这个 url 访问它: http://localhost:8008/image.jpg

这里app.use('/hiddenfolder', express.static(__dirname+'/mystaticcontent/')); 您隐藏文件夹的真实名称,图像可在http://localhost:8008/hiddenfolder/image.jpg

如果您不想使用 express,也许您应该查看https://www.npmjs.com/package/serve-static 以获取有关如何编写自己的静态模块的灵感。

希望能帮助到你!

*** 我找到了一种更简单的方法来使用nodejs文档中提供的node-static库来提供静态文件***

var static = require('node-static');
var http = require('http');

var file = new(static.Server)(__dirname);

http.createServer(function (req, res) {
  file.serve(req, res);
}).listen(8080);

相同的链接在此处NODE JS Docs

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM