简体   繁体   English

nodejs web root

[英]nodejs web root

I was under the impression that when you run a nodejs webserver the root of the web is the folder containing the js file implementing the webserver. 我的印象是,当你运行nodejs webserver时,web的根目录是包含实现webserver的js文件的文件夹。 So if you have C:\\foo\\server.js and you run it, then "/" refers to C:\\foo and "/index.htm" maps to C:\\foo\\index.htm 因此,如果你有C:\\ foo \\ server.js并运行它,那么“/”指的是C:\\ foo和“/index.htm”映射到C:\\ foo \\ index.htm

I have a file server.js with a sibling file default.htm, but when I try to load the contents of /default.htm the file is not found. 我有一个带有兄弟文件default.htm的文件server.js,但是当我尝试加载/default.htm的内容时,找不到该文件。 An absolute file path works. 绝对文件路径有效。

Where is "/" and what controls this? “/”在哪里以及控制它的是什么?


Working up a repro I simplified it to this: 编写一个repro我简化了它:

var fs = require('fs');
var body = fs.readFileSync('/default.htm');

and noticed it's looking for this 并注意到它正在寻找这个

Error: ENOENT, no such file or directory 'C:\default.htm'

So "/" maps to C:\\ 所以“/”映射到C:\\

Is there a way to control the mapping of the web root? 有没有办法控制Web根的映射?


I notice that relative paths do work. 我注意到相对路径确实有效。 So 所以

var fs = require('fs');
var body = fs.readFileSync('default.htm');

succeeds. 成功。

I believe my confusion arose from the coincidental placement of my original experiment's project files at the root of a drive. 我相信我的困惑源于我原来的实验项目文件巧合地放置在驱动器的根部。 This allowed references to /default.htm to resolve correctly; 这允许正确解析对/default.htm的引用; it was only when I moved things into a folder to place them under source control that this issue was revealed. 只有当我将事物移动到文件夹中以将它们置于源代码管理之下时才会显示此问题。

I will certainly look into express, but you haven't answered my question: is it possible to remap the web root and if so how? 我一定会调查快递,但你没有回答我的问题:是否有可能重新映射网络根目录,如果是,如何?

As a matter of interest this is server.js as it currently stands 感兴趣的是这是目前的server.js

var http = require('http');
var fs = require('fs');
var sys = require('sys');
var formidable = require('formidable');
var util = require('util');
var URL = require('url');
var QueryString = require('querystring');
var mimeMap = { htm : "text/html", css : "text/css", json : "application/json" };
http.createServer(function (request, response) {
  var body, token, value, mimeType;
  var url = URL.parse(request.url);
  var path = url.pathname;
  var params = QueryString.parse(url.query);  
  console.log(request.method + " " + path);  
  switch (path) {
    case "/getsettings":
      try {
        mimeType = "application/json";
        body = fs.readFileSync("dummy.json"); //mock db 
      } catch(exception) {
        console.log(exception.text);
        body = exception;
      }
      break;  
    case "/setsettings":
      mimeType = "application/json";
      body="{}";
      console.log(params);
      break;  
    case "/": 
      path = "default.htm";
    default:
      try { 
        mimeType = mimeMap[path.substring(path.lastIndexOf('.') + 1)];
        if (mimeType) {
         body = fs.readFileSync(path);
        } else {
          mimeType = "text/html";
          body = "<h1>Error</h1><body>Could not resolve mime type from file extension</body>";
        }
      } catch (exception) {
        mimeType = "text/html";
        body = "<h1>404 - not found</h1>" + exception.toString();
      }
      break;
  }
  response.writeHead(200, {'Content-Type': mimeType});
  response.writeHead(200, {'Cache-Control': 'no-cache'});
  response.writeHead(200, {'Pragma': 'no-cache'});
  response.end(body);  
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');

I'm not completely certain what you mean by "routes" but I suspect that setsettings and getsettings are the sort of thing you meant, correct me if I'm wrong. 我并不完全确定你所说的“路线”是什么意思,但我怀疑你的意思是设置和设置,如果我错了,请纠正我。


Nodejs does not appear to support arbitrary mapping of the web root. Nodejs似乎不支持Web根的任意映射。

All that is required is to prepend absolute web paths with a period prior to using them in the file system: 所需要的只是在文件系统中使用它们之前用一段时间预先设置绝对Web路径:

var URL = require('url');
var url = URL.parse(request.url);
var path = url.pathname;
if (path[0] == '/')
  path = '.' + path;

While you're correct that the root of the server is the current working directory Node.js won't do a direct pass-through to the files on your file system, that could be a bit of a security risk after all. 虽然你是正确的,服务器的根目录是当前的工作目录Node.js不会直接传递给你的文件系统上的文件,毕竟这可能有点安全风险。

Instead you need to provide it with routes that then in turn provide content for the request being made. 相反,您需要为其提供路由,然后这些路由又为正在进行的请求提供内容。

A simple server like 像一个简单的服务器

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');

Will just capture any request and respond in the same way (but doesn't read the file system). 将捕获任何请求并以相同的方式响应(但不读取文件系统)。

Now if you want to serve out file contents you need to specify some way to read that file into the response stream, this can be done a few ways: 现在,如果要提供文件内容,则需要指定一些方法将该文件读入响应流,这可以通过以下几种方式完成:

  1. You can use the fs API to find the file on disk, read its contents into memory and then pipe them out to the response. 您可以使用fs API在磁盘上查找文件,将其内容读入内存,然后将其传输到响应中。 This is a pretty tedious approach, especially when you start getting a larger number of files, but it does allow you very direct control over what's happening in your application 这是一种非常繁琐的方法,特别是当您开始获取大量文件时,它确实允许您直接控制应用程序中发生的事情
  2. You can use a middleware server like express.js , which IMO is a much better approach to do what you're wanting to do. 你可以使用像express.js这样的中间件服务器,IMO是一个更好的方法来做你想做的事情。 There's plenty of questions and answers on using Express here on StackOverflow, this is a good example of a static server which is what you talk about 在StackOverflow上使用Express这里有很多问题和答案, 这是你所谈论的静态服务器的一个很好的例子

Edit 编辑

With the clarification of the question the reason: 随着问题的澄清原因:

var body = fs.readFileSync('/default.htm');

Results in thinking the file is at C:\\default.htm is because you're using an absolute path not a relative path. 认为文件位于C:\\default.htm是因为您使用的是绝对路径而不是相对路径。 If you had: 如果你有:

var body = fs.readFileSync('./default.htm');

It would then know that you want to operate relative to the current working directory. 然后它会知道您想要相对于当前工作目录进行操作。 / is from the root of the partition and ./ is from the current working directory . / 来自分区的根,./ 来自当前工作目录

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

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