1. 程式人生 > 程式設計 >Node.js 中判斷一個檔案是否存在

Node.js 中判斷一個檔案是否存在

記錄一些 Node.js 應用中的小知識點,如果你 Google/Baidu “Node.js 如何判斷檔案是否存在” 發現給出的很多答案還是使用的 fs.exists,這裡不推薦使用 fs.exists 你可以選擇 fs.stat 或 fs.access。

為什麼不推薦 fs.exists

我們在設計一個回撥函式時,通常會遵循一個原則 “ 錯誤優先的回撥函式”,也就是返回值的第一個引數為錯誤資訊,用以驗證是否出錯,其它的引數則用於返回資料。

如下所示為 fs.exists 的使用示例,直接返回了一個布林值,違背了 “錯誤優先的回撥函式” 這一設計原則,這是一方面原因。

fs.exists('/etc/passwd',(exists) => { 
 console.log(exists ? '存在' : '不存在'); 
}); 

另外一個是 不推薦在 fs.open()、 fs.readFile() 或 fs.writeFile() 之前使用 fs.exists() 判斷檔案是否存在,因為這樣會引起 競態條件,如果是在多程序下,程式的執行不完全是線性的,當程式的一個程序在執行 fs.exists 和 fs.writeFile() 時,其它程序是有可能在這之間更改檔案的狀態,這樣就會造成一些非預期的結果。

不推薦:

(async () => { 
 const exists = await util.promisify(fs.exists)('text.txt'); 
 console.log(exists); 
 await sleep(10000); 
 if (exists) { 
  try { 
   const res = await util.promisify(fs.readFile)('text.txt',{ encoding: 'utf-8' }); 
   console.log(res); 
  } catch (err) { 
   console.error(err.code,err.message); 
   throw err; 
  } 
 } 
})(); 

推薦:

(async () => { 
 try { 
  const data = await util.promisify(fs.readFile)('text.txt',{ encoding: 'utf-8' }); 
  console.log(data); 
 } catch (err) { 
  if (err.code === 'ENOENT') { 
   console.error('File does not exists'); 
  } else { 
   throw err; 
  } 
 } 
})(); 

目前 fs.exists 已被廢棄,另外需要清楚, 只有在檔案不直接使用時才去檢查檔案是否存在,下面推薦幾個檢查檔案是否存在的方法。

使用 fs.stat

fs.stat返回一個 fs.Stats 物件,該物件提供了關於檔案的很多資訊,例如檔案大小、建立時間等。其中有兩個方法 stats.isDirectory()、stats.isFile() 用來判斷是否是一個目錄、是否是一個檔案。

const stats = await util.promisify(fs.stat)('text1.txt'); 
console.log(stats.isDirectory()); // false 
console.log(stats.isFile()); // true 

若只是檢查檔案是否存在,推薦使用下面的 fs.access。

使用 fs.access

fs.access 接收一個 mode 引數可以判斷一個檔案是否存在、是否可讀、是否可寫,返回值為一個 err 引數。

const file = 'text.txt'; 
 
// 檢查檔案是否存在於當前目錄中。 
fs.access(file,fs.constants.F_OK,(err) => { 
 console.log(`${file} ${err ? '不存在' : '存在'}`); 
}); 
 
// 檢查檔案是否可讀。 
fs.access(file,fs.constants.R_OK,(err) => { 
 console.log(`${file} ${err ? '不可讀' : '可讀'}`); 
}); 
 
// 檢查檔案是否可寫。 
fs.access(file,fs.constants.W_OK,(err) => { 
 console.log(`${file} ${err ? '不可寫' : '可寫'}`); 
}); 
 
// 檢查檔案是否存在於當前目錄中、以及是否可寫。 
fs.access(file,fs.constants.F_OK | fs.constants.W_OK,(err) => { 
 if (err) { 
  console.error( 
   `${file} ${err.code === 'ENOENT' ? '不存在' : '只可讀'}`); 
 } else { 
  console.log(`${file} 存在,且可寫`); 
 } 
}); 

同樣的也不推薦在 fs.open()、 fs.readFile() 或 fs.writeFile() 之前使用 fs.exists() 判斷檔案是否存在,會引起競態條件。

Reference

http://nodejs.cn/api/fs.html

以上就是Node.js 中判斷一個檔案是否存在的詳細內容,更多關於Node.js 判斷檔案是否存在的資料請關注我們其它相關文章!