【问题标题】:Find first file with given filename查找具有给定文件名的第一个文件
【发布时间】:2022-02-07 22:57:48
【问题描述】:

您好,我正在尝试查找具有给定文件名的第一个文件(一段文件名)。

效果很好,但需要一段时间才能得到结果

有代码

const fs = require("fs");

const dirCheckIn =
    "\\\\192.168.2.4\\Photos";


exports.checkUploadedFiles = (req, res) => {
    let fileName = req.params.filename;

    const getAllFiles = function (dirPath, arrayOfFiles) {
        files = fs.readdirSync(dirPath);

        arrayOfFiles = arrayOfFiles || [];

        files.forEach(function (file) {
            if (fs.statSync(dirPath + "/" + file).isDirectory()) {
                arrayOfFiles = getAllFiles(dirPath + "/" + file, arrayOfFiles);
            } else {
                arrayOfFiles.push(file);
            }
        });

        return arrayOfFiles;
    };

    const uploadedFiles = getAllFiles(inventDirCheckIn);
    console.log(uploadedFiles)
    let result = uploadedFiles.find(
        (result) => result.startsWith(fileName));

    if (!result) {
        res.send('nothing found')
    } else if (result) {
        res.send(result)
    }

}

它工作正常,但例如,如果我有超过 7000 张照片,则需要大约 5 秒才能获得结果。 也许有更聪明的解决方案?

我怎样才能更好地做到这一点?我想检查文件是否上传到照片目录。 我得到了简单的api路由/api/getUploadedFiles/:filename

我也想使用startsWith,因为有时我不知道文件的全名

【问题讨论】:

  • 我认为您应该尝试使用fs.open()fs.readFile()fs.writeFile() 打开文件,然后处理错误。如果存在,它将打开,如果不存在,则处理错误。来源:nodejs.org/api/fs.html#fsstatpath-options-callback >不建议在调用 fs.open()、fs.readFile() 或 fs.writeFile() 之前使用 fs.stat() 检查文件是否存在。相反,用户代码应该直接打开/读取/写入文件并处理文件不可用时引发的错误。
  • 我不想打开它。如果存在,我只想要真或假,否则为假
  • '使用fs.stat() 来检查是否存在' - 我认为这应该可以完成这项工作?
  • 或 '要检查文件是否存在而不随后对其进行操作,建议使用fs.access()。'
  • 好的,我也会检查一下@matzar

标签: javascript node.js


【解决方案1】:

/**
 *
 * @param filePath path to file which is to be checked if it exists.
 */
private checkFileExistsSync(filePath: string) {
  let flag = true;
  try {
    fs.accessSync(filePath, fs.constants.F_OK);
  } catch (e) {
    flag = false;
  }
  return flag;
}

// Example usage
// path to the file
const dirCheckIn =
    "\\\\192.168.2.4\\Photos";
    
if (checkFileExistsSync(dirCheckIn)) {
  // if the file exists do something...
}

if (!checkFileExistsSync(dirCheckIn)) {
  // if the file doesn't exists do something...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-02
    • 2012-04-02
    • 2017-05-12
    • 2011-03-10
    相关资源
    最近更新 更多