node.js - 检查我的服务器上是否存在文件-node js
问题描述
当我使用像“ http://localhost:8080/?file=index.js ”这样的url查询时,我总是得到“文件不存在”。
该文件确实存在。有什么建议么?
目的:查找文件是否存在于我的服务器上。文件名必须在文件参数中。
let http = require("http");
let fs = require("fs");
http.createServer(function(req,res) {
let url2 = req.url;
if(fs.existsSync(url2.file)==true)
{
res.end("The file exists");
}
else{
res.end("The file doesn't exists");
}
}).listen(8080);
谢谢 !
解决方案
req.url
在你的情况下将是/?file=index.js
。而且,当你这样做时url2.file
是undefined
这样的:
if(fs.existsSync(url2.file)==true)
你正在运行:
if(fs.existsSync(undefined)==true)
这永远不会是真的。
如果您想要一个特定的查询参数,例如file=index.js
,那么您必须将该 URL 解析为一个数据结构,然后允许您访问该.file
属性。
有几种方法可以解析查询字符串。
您可以使用URL 库并解析整个 URL,然后它会为您提供它所称的 URLSearchParams。
您可以自己获取查询字符串,并使用queryString 库将查询字符串解析为它的一部分。
您可以使用像 Express 这样的框架,它会自动为您解析查询字符串参数并将它们放入
req.query
.
这是使用 queryString 模块的实现:
const http = require("http");
const fs = require("fs");
const querystring = require('querystring');
http.createServer(function(req,res) {
let index = req.url.indexOf("?");
if (index !== -1) {
let qs = req.url.slice(index + 1);
let qsObj = querystring.parse(qs);
if (qsObj.file) {
if (fs.existsSync(qsObj.file)) {
res.end(`The file ${qsObj.file} exists`);
} else {
res.end(`The file ${qsObj.file} does not exist`);
}
return;
}
}
res.end("Invalid request, no file specified");
}).listen(8080);
或者,这是一个使用 URL 类的实现:
const http = require("http");
const fs = require("fs");
http.createServer(function(req,res) {
urlObj = new URL(req.url, `http://${req.headers.host}`);
let file = urlObj.searchParams.get("file");
if (file) {
if (fs.existsSync(file)) {
res.end(`The file ${file} exists`);
} else {
res.end(`The file ${file} does not exist`);
}
return;
}
res.end("Invalid requeset, no file specified");
}).listen(8080);
推荐阅读
- javascript - 仅通过调用 JavaScript 函数来显示进度微调器
- sql - 将两个表与一些业务逻辑合并以实现溢出
- javascript - 从 JS 数组返回信息以用作全局变量
- r - 如何创建一个可以变成矩阵的容器
- android - onClick(CoroutineContext) 单元已弃用 Kotlin Anko
- python - nosetest - 运行子目录中的所有测试
- r - 计算R中数组中匹配配对值的数量
- python - 以正确的格式将 API 结果附加到现有 CSV 文件中(新标头 + API 结果)
- excel - 公式自动填充日期列适用于工作表但不适用于表单
- swagger - Swagger-Springfox + WebFlux + JavaX 验证 (JSR 303) 支持