Nodejs初学者关于path.exists更改为fs.exists的疑问

Nodejs初学者关于path.exists更改为fs.exists的疑问

场景: 我的安装的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 回复

Node.js 初学者关于 path.exists 更改为 fs.exists 的疑问

场景:

我安装的是 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 已经被弃用,应该使用 fs.exists
    // path.exists(absPath, function(exists) {
    fs.exists(absPath, function(exists) {
        if(exists) {
            fs.readFile(absPath, function(err, data) {
                if(err) {
                    response.writeHead(500, {"Content-Type": "text/plain"});
                    response.end('Internal Server Error');
                } else {
                    response.writeHead(200, {"Content-Type": "text/html"});
                    response.write(data);
                    response.end();
                }
            });
        } else {
            response.writeHead(404, {"Content-Type": "text/plain"});
            response.end('404 File not found.');
        }
    });
}).listen(8888);

console.log("Server running at http://127.0.0.1:8888/");

问题描述:

你提到的错误信息是由于 path.exists 已经被弃用,并且在较新的 Node.js 版本中已经被移除。你应该使用 fs.exists 来检查文件是否存在。

修改后的代码解释:

  1. 引入模块:引入了 http, fs, urlutilpath 模块。
  2. 创建服务器:创建了一个 HTTP 服务器,并监听端口 8888。
  3. 解析请求路径:从请求 URL 中解析出路径。
  4. 构建绝对路径:将请求路径与项目根目录下的 webroot 目录拼接成绝对路径。
  5. 检查文件是否存在:使用 fs.exists 替换掉已被弃用的 path.exists 方法。
  6. 读取文件内容:如果文件存在,则读取文件内容并返回给客户端;如果不存在,则返回 404 错误。

注意事项:

  • 在较新的 Node.js 版本中,fs.exists 也被认为是已弃用的方法。推荐使用 fs.promises.accessfs.stat 方法来替代。
  • 为了更好的错误处理,建议在 fs.readFile 中添加错误处理逻辑。

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

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

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

感谢感谢!!!

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

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

在Node.js中,path.exists已经被废弃,并且被fs.exists所取代。你的错误信息也提示了这一点,建议使用fs.exists

以下是修改后的代码示例:

var http = require("http"),
    fs = require("fs"),
    urlutil = require("url");

http.createServer(function(request, response) {
    var urlpath = urlutil.parse(request.url).pathname;
    var absPath = __dirname + "/webroot" + urlpath;

    // 使用 fs.exists 替代 path.exists
    fs.exists(absPath, function(exists) {
        if (exists) {
            fs.readFile(absPath, function(err, data) {
                if (err) {
                    response.end('500 Internal Server Error');
                    return;
                }
                response.write(data);
                response.end();
            });
        } else {
            response.end('404 File not found.');
        }
    });
}).listen(8888);

关键点解释:

  1. fs.exists:用于检查文件或目录是否存在。
  2. fs.readFile:用于读取文件内容。注意,这里添加了错误处理逻辑(if (err)),以确保当文件读取失败时,能够正确返回错误信息。
  3. 路径拼接:通过 __dirname 获取当前文件所在目录,并与请求的路径拼接得到绝对路径。

通过这些调整,你可以避免之前的错误,并确保程序正常运行。如果仍然遇到问题,可能是文件路径或文件权限方面的问题,需要进一步检查。

回到顶部