简体   繁体   English

如何在本地通过Node.js提供静态文件?

[英]How do I serve static files through Node.js locally?

I have the following file locations : 我有以下文件位置:

file:///Users/MyName/Developer/sitename/scripts (contains all .js files..)
file:///Users/MyName/Developer/sitename/css (contains all .css files..)
file:///Users/MyName/Developer/sitename/images (contains all .jpg/png/etc. files..)
file:///Users/MyName/Developer/sitename/sitename.html
file:///Users/MyName/Developer/sitename/server.js

Inside sitename.html I load all necessary files as follows for example : sitename.html里面我按如下方式加载所有必要的文件,例如:

<html>
  <head>
    <script src="scripts/somefile.js"></script>
  </head>
  ...
</html>

So whenever I open up file:///Users/MyName/Developer/sitename/sitename.html everything works fine. 所以每当我打开file:///Users/MyName/Developer/sitename/sitename.html一切正常。

However, whenever I try to load file:///Users/MyName/Developer/sitename/sitename.html via a local Node.js server that I've setup (server file location : file:///Users/MyName/Developer/sitename/server.js ) as follows : 但是,每当我尝试通过我设置的本地Node.js服务器加载file:///Users/MyName/Developer/sitename/sitename.html (服务器文件位置: file:///Users/MyName/Developer/sitename/server.js )如下:

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

fs.readFile('./sitename.html', function (err, html) 
{
    if (err) throw err; 

    http.createServer(function (request,response)
    {  
        // serve site
        if (request.url === "/")
        {
            response.writeHeader(200, {"Content-Type": "text/html"});  
            response.write(html);  
        }
        response.end(); 
    }).listen(8080); 
});

sitename.html is found and loaded but all the other files that are supposed to load through it fail to load because they're all given the prefix http://localhost:8080/ ( http://localhost:8080/scripts/somefile.js is not a valid file path for example). 发现并加载了sitename.html ,但是所有其他应该通过它加载的文件都无法加载,因为它们都被赋予了前缀http://localhost:8080/http://localhost:8080/scripts/somefile.js不是有效的文件路径。

It looks like as soon as the server is created (inside http.createServer(.....); ) the context changes and the parent directory now becomes http://localhost:8080/ instead of file:///Users/MyName/Developer/sitename/ which makes sense I guess but is not very helpful when using files that are still stored locally. 它看起来就像创建服务器一样(在http.createServer(.....);内部),上下文发生变化,父目录现在变为http://localhost:8080/而不是file:///Users/MyName/Developer/sitename/file:///Users/MyName/Developer/sitename/很有意义,但在使用仍然存储在本地的文件时不是很有帮助。

How do I work around that? 我该如何解决这个问题? Is the fact that I'm storing server.js (just for the time being) in the same directory making things even more confusing? 事实上,我正在将server.js (暂时只存储在同一目录中)存储起来,使事情变得更加混乱?

Thanks! 谢谢!

The easiest solution I found on serving local static files is to use Http-Server . 我在提供本地静态文件时找到的最简单的解决方案是使用Http-Server

Its usage is dead simple. 它的用法很简单。 After installing it globally 全局安装后

 npm install http-server -g

Go to the root directory you want to serve 转到要提供的根目录

cd <dir>
http-server

That's it! 而已!

You're able to load the files using the file:// URL because it's a feature of your web browser. 您可以使用file:// URL加载文件,因为它是您的Web浏览器的一项功能。

When loading the address http://localhost:8080 you're no longer leveraging the browser's ability to serve the files (you're accessing the Node.js server). 加载地址http://localhost:8080您不再利用浏览器提供文件的能力(您正在访问Node.js服务器)。 The HTML page being served contains relative paths which work in conjunction with the current hostname to load the assets. 正在提供的HTML页面包含相对路径,这些路径与当前主机名一起使用以加载资产。

There is a multitude of options for serving the assets. 提供资产有多种选择。

You could serve the files with Node.js: 您可以使用Node.js提供文件:

Alternatively you could use a web server to serve the files for you. 或者,您可以使用Web服务器为您提供文件。 This is likely to be the most performant option. 这可能是性能最佳的选择。 Here is an example of serving static content with nginx. 以下是使用nginx提供静态内容的示例

The problem is that while you've defined the path for one static resource (sitename.html), you haven't defined the path for all the other static resources it references (eg somefile.js). 问题是,虽然您已经为一个静态资源(sitename.html)定义了路径,但您还没有为它引用的所有其他静态资源定义路径(例如somefile.js)。 Assuming the following file structure, below contains the server code that handles loading static resources relative to your public directory (www), without using external modules. 假设以下文件结构,下面包含处理相对于公共目录(www)加载静态资源的服务器代码,而不使用外部模块。 (partly taken from here ) (部分取自这里

project/
    server/    
        server.js
        dispatcher.js
    www/
        index.html
        js/ (your javascript files)
        css/ (your css files)

server.js : server.js

var http = require('http');
http.createServer(handleRequest).listen(8124, "127.0.0.1");
var dispatcher = require('./dispatcher.js');

function handleRequest(req, res) {
    try {
        console.log(req.url);
        dispatcher.dispatch(req, res);
    } catch(err) {
        console.log(err);
    }
}

dispatcher.js : dispatcher.js

var fs = require('fs');
var path = require('path');

this.dispatch = function(request, response) {
    //set the base path so files are served relative to index.html
    var basePath = "../www";
    var filePath = basePath + request.url;

    var contentType = 'text/html';
    var extname = path.extname('filePath');
    //get right Content-Type
    switch (extname) {
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.css':
            contentType = 'text/css';
            break;
    }

    //default to index.html
    if (filePath == basePath + "/") {
        filePath = filePath + "index.html";
    }

    //Write the file to response
    fs.readFile(filePath, function(error, content) {
        if (error) {
            response.writeHead(500);
            response.end();
        } else {
            response.writeHead(200, {'Content-Type': contentType});
            response.end(content, 'utf-8');
        }
    });

}

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

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