简体   繁体   English

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

[英]How to serve static files in vanilla nodeJS

To preface this, I am currently learning how to use vanilla nodeJS to host html files for a personal project.首先,我目前正在学习如何使用 vanilla nodeJS 来托管个人项目的 html 文件。 I am using the following code to do this.我正在使用以下代码来执行此操作。 I realize that in order to display images with html I need to publicly serve the files;我意识到为了用 html 显示图像,我需要公开提供这些文件; however, I am not sure how to do this with the provided code below.但是,我不确定如何使用下面提供的代码执行此操作。 I appreciate any feedback and contributions on how to achieve this.我感谢有关如何实现这一目标的任何反馈和贡献。

 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>

Hei, try this piece of code:嘿,试试这段代码:

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");

So, because for the image you did not have a case in your switch the default was used.因此,因为对于您的开关中没有案例的图像,使用了默认值。 I specified in the default case what to do.我在默认情况下指定了要做什么。 As you can see if you end up with 100 static files you have to specify a case for each and every file.如您所见,如果最终得到 100 个静态文件,则必须为每个文件指定一个大小写。 Note that the example above will work only for jpg images .请注意,上面的示例仅适用于 jpg 图像。 This will be very hard to maintain and not recomended because it will (possibly) mix your statics with the website's logic.这将很难维护并且不推荐,因为它会(可能)将您的静态数据与网站的逻辑混合在一起。

The easiest way to achieve what you want is to use express module, it already has this functionality and it is very, very easy to use.实现您想要的最简单方法是使用 express 模块,它已经具有此功能并且非常非常易于使用。

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

For the first app.use(express.static(__dirname + '/mystaticcontent'));对于第一个app.use(express.static(__dirname + '/mystaticcontent')); if you put image.jpg in this folder, you can access it using this url: http://localhost:8008/image.jpg如果你把 image.jpg 放在这个文件夹中,你可以使用这个 url 访问它: http://localhost:8008/image.jpg

Here app.use('/hiddenfolder', express.static(__dirname+'/mystaticcontent/'));这里app.use('/hiddenfolder', express.static(__dirname+'/mystaticcontent/')); you hide the real name of the folder , the image is accessible at http://localhost:8008/hiddenfolder/image.jpg您隐藏文件夹的真实名称,图像可在http://localhost:8008/hiddenfolder/image.jpg

If you don't want to use express, maybe you should have a look at https://www.npmjs.com/package/serve-static get inspired about how to write your own statics module.如果您不想使用 express,也许您应该查看https://www.npmjs.com/package/serve-static 以获取有关如何编写自己的静态模块的灵感。

Hope it helps!希望能帮助到你!

*** I have found an easier way to serve static files using node-static library provided in nodejs docs *** *** 我找到了一种更简单的方法来使用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);

A link to the same is here NODE JS Docs相同的链接在此处NODE JS Docs

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

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