【问题请教】关于fs.exists的判断问题
发布于 11 年前 作者 borisyu 10578 次浏览 最后一次编辑是 8 年前

今天依然重复写个简单的web server例子,但是在fs.exists判断上出了问题。代码如下:

http.createServer(function(req, res){
    var reqPath = url.parse(req.url).pathname;
    
    fs.exists(reqPath, function(exists){
        if(!exists){
            consloe.log(reaPath + ' not exists.');
        }else{
          //do something
        }
    });
});

在浏览器请求http://localhost:8888/index.html 时,console输出的信息居然是 “/index.html not exists.”。 首先,index.html是存在的,并且与server.js同在一个目录下。

目录结构如下: http/ |-server.js |-index.html

当我把if判断改成这样,就可以顺利执行do something了 if(exists){ console.log(reqPath + ’ not exists.’); }else{ //do something }

按理说,文件存在,exists返回的是true,否则返回false。但为什么我这里的逻辑居然是相反的?

7 回复

你的req.path/index.html,而你的文件是在server.js同一个目录下的…你用fs.read('/index.html', callback)会去读根目录下的index.html文件,当然会不存在。

目录结构如下: http/ |-server.js |-index.html

在http目录下运行node server.js后,此时的网站的根目录应该就是http/目录吧?

fs模块的根目录是系统根目录…

嗯!在改了if判断后,通过输出readFile的err信息,终于发现这个问题了。原来实际是请求根目录下的index.html,而非http/index.html

thanks a lot!

我是在win下安装node的,安装路径是F:/,安装完毕后,在F盘下生成以下路径F:/nodejs

在F:/nodejs/目录下,我有两个node的程序,分别是 F:/nodejs/project/fileserver/ |-resource/style.css |-index.js |-server.js |-route.js |-requestHandler.js F:/nodejs/project/http/ |-server.js |-index.html

问题就在这里,刚才在http/下运行node server.js,无法请求localhost/index.html,而在fileserver/下运行node index.js,可以正常读取localhost/resource/style.css

这样的话,估计跟网站的根目录,是跟fs模块所在目录没关吧?网站的根目录,不应该是根据node js 入口文件所在目录而定的吗?

@borisyu node不单纯一个web服务器,fs也不是为web服务器而服务的。 如何写一个静态服务器,可以看看这个文章Node.js静态文件服务器实战

@dead_horse 我那个fileserver就是参考这个文章写的。T_T 我把http/目录下面的两个文件,放到F:/根目录下,就完全没问题。这个路径问题还是要继续折腾一下

回到顶部