检查我的服务器上是否存在文件 - node js

Check if file exists on my sever - node js

当我使用像“http://localhost:8080/?file=index.js”这样的 url 查询时,我总是得到 "the file doesn't exist".

文件确实存在。 有什么建议吗?

目的:查找文件是否存在于我的服务器上。文件名必须在文件参数中。

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.fileundefined 所以当你这样做时:

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

你是 运行:

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

这永远不会是真的。


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

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

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

  2. 您可以自己获取查询字符串,然后使用 queryString library 将查询字符串解析成它的片段。

  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 class:

的实现
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);