gpt4 book ai didi

javascript - NodeJS - fs.exists() 抛出错误但文件在那里?

转载 作者:行者123 更新时间:2023-11-30 06:20:31 27 4
gpt4 key购买 nike

我尝试检查服务器上是否存在文件(例如 css 文件):

// parse url and extract URL path
var pathname = url.parse(req.url).pathname;


fs.exists(pathname, function (exist) {

// if the file is not found, return 404
if(!exist) {
console.log('NOT EXISTING: '+pathname);
res.statusCode = 404;
res.end(`File ${pathname} not found!`);
return;
}

..... blah blah
}

文件在那里,但输出是:不存在:/assets/css/bootstrap.min.css

我做错了什么?

最佳答案

尝试在路径前添加 __dirname:

var pathname = url.parse(req.url).pathname;

fs.exists(__dirname + pathname, function (exist) {

// if the file is not found, return 404
if(!exist) {
console.log('NOT EXISTING: '+pathname);
res.statusCode = 404;
res.end(`File ${pathname} not found!`);
return;
}

..... blah blah
}

当路径以 / 开头时,NodeJS 将从操作系统的根目录开始查找文件。通过提供 __dirname,您告诉 NodeJS 从您的当前目录搜索。

关于javascript - NodeJS - fs.exists() 抛出错误但文件在那里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53426170/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com