首页 > 解决方案 > 检查我的服务器上是否存在文件-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);

谢谢 !

标签: node.jsfilesystems

解决方案


req.url在你的情况下将是/?file=index.js。而且,当你这样做时url2.fileundefined这样的:

if(fs.existsSync(url2.file)==true)

你正在运行:

if(fs.existsSync(undefined)==true)

这永远不会是真的。


如果您想要一个特定的查询参数,例如file=index.js,那么您必须将该 URL 解析为一个数据结构,然后允许您访问该.file属性。

有几种方法可以解析查询字符串。

  1. 您可以使用URL 库并解析整个 URL,然后它会为您提供它所称的 URLSearchParams。

  2. 您可以自己获取查询字符串,并使用queryString 库将查询字符串解析为它的一部分。

  3. 您可以使用像 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);

推荐阅读