Javascript 为什么Node.js只识别绝对路径?;

Javascript 为什么Node.js只识别绝对路径?;,javascript,html,node.js,npm,server,Javascript,Html,Node.js,Npm,Server,我创建了一个名为nodes的文件,然后用npminit初始化该文件,主js文件名为main.js。我还在文件中创建了index.html和index.css,之后我想使用Node.js呈现这个index.html,所以我在main.js中写道: const http = require('http'); const fs = require('fs'); const hostname = '127.0.0.1'; const port = 9000; const mainHTML = './i

我创建了一个名为nodes的文件,然后用
npminit
初始化该文件,主js文件名为
main.js
。我还在文件中创建了index.html和index.css,之后我想使用
Node.js
呈现这个index.html,所以我在
main.js
中写道:

const http = require('http');
const fs = require('fs');

const hostname = '127.0.0.1';
const port = 9000;
const mainHTML = './index.html';

const server = http.createServer((req, res) => {
  fs.stat(`./${mainHTML}`, (err, stats) => {
    if(stats) {
      res.statusCode = 200;
      res.setHeader('Content-Type', 'text/html');
      fs.createReadStream(mainHTML).pipe(res);
    }
  });
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
我用
node desktop/nodes
命令打开了服务器,但是node.js找不到该文件

在我将相对路径更改为绝对路径之前,
Node.js
将识别它:

const mainHTML = 'desktop/nodes/index.html';

为什么会这样?如果我想使用相对路径,我该怎么做?

您正在创建http服务器,它将其路径创建为基本路径,因此它只理解将该基本路径作为相对路径的路径。如果要使用相对路径,则需要解析该路径

您可以使用“路径”库

const path = require('path')
// To resolve parent path
path.resolve('..', __dirname__)

使用相对路径访问node.js中的文件时,将相对于进程当前工作目录的值访问该文件。注意,在node.js的模块化世界中,当前工作目录可能与模块所在的目录相同,也可能不同。而且,您的代码可以将当前工作目录更改为您希望的任何目录

在modular node.js代码中,有一种编程愿望,即访问与当前模块代码加载所在目录相关的内容。这使您能够使用相对路径,以便应用程序/模块可以在任何地方工作,但它可以确保您将获得所需的文件。为此,通常使用模块特定变量
\uu dirname
。这是从中加载当前模块的目录。如果它是node.js启动时使用的主脚本,那么它就是该脚本的目录

因此,要从与当前脚本相同的目录中获取文件,可以执行以下操作:

const mainHTML = 'index.html';
fs.createReadStream(path.join(__dirname, mainHTML)).pipe(res);
const mainHTML = 'public/index.html';
fs.createReadStream(path.join(__dirname, mainHTML)).pipe(res);
const mainHTML = '../public/index.html';
fs.createReadStream(path.join(__dirname, mainHTML)).pipe(res);
要访问脚本所在子目录
public
中的文件,可以执行以下操作:

const mainHTML = 'index.html';
fs.createReadStream(path.join(__dirname, mainHTML)).pipe(res);
const mainHTML = 'public/index.html';
fs.createReadStream(path.join(__dirname, mainHTML)).pipe(res);
const mainHTML = '../public/index.html';
fs.createReadStream(path.join(__dirname, mainHTML)).pipe(res);
要访问与脚本所在位置处于同一级别(公共父目录)的不同子目录中的文件,可以执行以下操作:

const mainHTML = 'index.html';
fs.createReadStream(path.join(__dirname, mainHTML)).pipe(res);
const mainHTML = 'public/index.html';
fs.createReadStream(path.join(__dirname, mainHTML)).pipe(res);
const mainHTML = '../public/index.html';
fs.createReadStream(path.join(__dirname, mainHTML)).pipe(res);

所有这些使用的路径都与脚本本身所在的位置相关,不取决于模块/脚本的加载方式或应用程序的当前工作目录。

我认为问题之一是
/
部分的重复<代码>常量mainHTML='./index.html'将mainHTML设置为“/index.html”,fs.stat()方法中的
/${mainHTML}
计算结果为
//index.html