當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js fs.exists(path, callback)用法及代碼示例

fs.exists(path, callback)

曆史
版本變化
v18.0.0

將無效回調傳遞給 callback 參數現在會拋出 ERR_INVALID_ARG_TYPE 而不是 ERR_INVALID_CALLBACK

v7.6.0

path 參數可以是使用 file: 協議的 WHATWG URL 對象。

v1.0.0

棄用自:v1.0.0

v0.0.2

添加於:v0.0.2

Stability: 0 - 已棄用:改用 fs.stat() fs.access()

參數

通過檢查文件係統來測試給定路徑是否存在。然後使用 true 或 false 調用 callback 參數:

import { exists } from 'node:fs';

exists('/etc/passwd', (e) => {
  console.log(e ? 'it exists' : 'no passwd!');
});

此回調的參數與其他 Node.js 回調不一致。通常,Node.js 回調的第一個參數是 err 參數,後麵可以選擇其他參數。 fs.exists() 回調隻有一個布爾參數。這是推薦使用 fs.access() 而不是 fs.exists() 的原因之一。

不建議在調用 fs.open()fs.readFile()fs.writeFile() 之前使用 fs.exists() 檢查文件是否存在。這樣做會引入競爭條件,因為其他進程可能會在兩次調用之間更改文件的狀態。相反,用戶代碼應該直接打開/讀取/寫入文件並處理文件不存在時引發的錯誤。

寫(不推薦)

import { exists, open, close } from 'node:fs';

exists('myfile', (e) => {
  if (e) {
    console.error('myfile already exists');
  } else {
    open('myfile', 'wx', (err, fd) => {
      if (err) throw err;

      try {
        writeMyData(fd);
      } finally {
        close(fd, (err) => {
          if (err) throw err;
        });
      }
    });
  }
});

寫(推薦)

import { open, close } from 'node:fs';
open('myfile', 'wx', (err, fd) => {
  if (err) {
    if (err.code === 'EEXIST') {
      console.error('myfile already exists');
      return;
    }

    throw err;
  }

  try {
    writeMyData(fd);
  } finally {
    close(fd, (err) => {
      if (err) throw err;
    });
  }
});

閱讀(不推薦)

import { open, close, exists } from 'node:fs';

exists('myfile', (e) => {
  if (e) {
    open('myfile', 'r', (err, fd) => {
      if (err) throw err;

      try {
        readMyData(fd);
      } finally {
        close(fd, (err) => {
          if (err) throw err;
        });
      }
    });
  } else {
    console.error('myfile does not exist');
  }
});

閱讀(推薦)

import { open, close } from 'node:fs';

open('myfile', 'r', (err, fd) => {
  if (err) {
    if (err.code === 'ENOENT') {
      console.error('myfile does not exist');
      return;
    }

    throw err;
  }

  try {
    readMyData(fd);
  } finally {
    close(fd, (err) => {
      if (err) throw err;
    });
  }
});

上麵的"not recommended" 示例檢查是否存在,然後使用該文件; "recommended" 示例更好,因為它們直接使用文件並處理錯誤(如果有)。

通常,僅當文件不會被直接使用時才檢查文件是否存在,例如當它的存在是來自另一個進程的信號時。

相關用法


注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 fs.exists(path, callback)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。