nodejs初学者:关于path.exists is now called `fs.exists`. undefined
发布于 11 年前 作者 lynnliu 16639 次浏览 最后一次编辑是 8 年前

场景: 我的安装的node-v0.10.5-x64

var http=require(“http”), fs=require(“fs”), urlutil=require(“url”), path=require(“path”);

http.createServer(function(request, response){

var urlpath = urlutil.parse(request.url).pathname;

var absPath = __dirname + "/webroot" + urlpath;

path.exists(absPath, function(exists) {
    if(exists) {
     
        fs.readFile(absPath,function(err, data) {
      
        //if(err) throw err;
        console.log(data);
        response.write(data);
        response.end();
});
    } else {
        
        response.end('404 File not found.');
    }
});

}).listen(8888);

======================================================= 报错的信息:

path.exists is now called fs.exists. undefined

http.js:780 throw new TypeError(‘first argument must be a string or Buffer’); ^ TypeError: first argument must be a string or Buffer at ServerResponse.OutgoingMessage.write (http.js:780:11) at E:\鎶€鏈偍澶嘰node.js\鑱婂ぉ瀹index.js:21:22 at fs.js:237:16 at Object.oncomplete (fs.js:107:15)

有人说 是版本的 问题,但是 我怎么换 都还是 报错!!! 求 高手 解决!!!!

6 回复

应该没有问题的, 你是不是在浏览器中只输入了 http://localhost:8888/ 应该再输入要访问的文件名,否则fs.readFile 读的就是个路径而不是文件,所以出错。

感谢,果真是这样的,代码没问题,也不是版本的问题! 是操作问题!!我最开始是在地址栏,直接访问:http://localhost:8888结果就出错了!!! 正确访问方式:http://loclahost:8888/index.html

index.html 这个文件在路径:项目根目录\webroot\index.html

感谢感谢!!!

建议阅读connect源代码,少走弯路

__dirname 是啥?传的值是啥样的?

@tsregll __dirname 是当前文件的目录,你可以console.log 打印看看

@tsregll

全局对象建议看看

回到顶部