[英]nodejs fs.exists()
我正在嘗試在節點腳本中調用fs.exists
但出現錯誤:
類型錯誤:對象 # 沒有方法“存在”
我試過用require('fs').exists
甚至require('path').exists
替換fs.exists()
(以防萬一),但這些都沒有在我的 IDE 中列出方法exists()
。 fs
在我的腳本頂部聲明為fs = require('fs');
我以前用它來讀取文件。
我如何調用exists()
?
您的 require 語句可能不正確,請確保您具有以下內容
var fs = require("fs");
fs.exists("/path/to/file",function(exists){
// handle result
});
在這里閱讀文檔
您應該改用fs.stats
或fs.access
。 從節點文檔中,不推薦使用(可能已刪除。)
如果您想做的不僅僅是檢查存在,文檔說使用fs.open
。 舉例
fs.access('myfile', (err) => {
if (!err) {
console.log('myfile exists');
return;
}
console.log('myfile does not exist');
});
不要使用 fs.exists請閱讀其 API 文檔以獲取替代方案
這是建議的替代方法:繼續打開文件,然后處理錯誤(如果有):
var fs = require('fs');
var cb_done_open_file = function(interesting_file, fd) {
console.log("Done opening file : " + interesting_file);
// we know the file exists and is readable
// now do something interesting with given file handle
};
// ------------ open file -------------------- //
// var interesting_file = "/tmp/aaa"; // does not exist
var interesting_file = "/some/cool_file";
var open_flags = "r";
fs.open(interesting_file, open_flags, function(error, fd) {
if (error) {
// either file does not exist or simply is not readable
throw new Error("ERROR - failed to open file : " + interesting_file);
}
cb_done_open_file(interesting_file, fd);
});
正如其他人所指出的那樣, fs.exists
已過時,部分是因為它采用的是單一的(success: boolean)
參數,而不是更常見的(error, result)
的參數目前幾乎其他任何地方。
但是, fs.existsSync
並沒有被棄用(因為它不使用回調,它只返回一個值),如果腳本的其余部分都依賴於檢查單個文件的存在,那么它可以使事情變得更容易處理回調或使用try
/ catch
包圍調用(在accessSync
的情況下):
const fs = require('fs');
if (fs.existsSync(path)) {
// It exists
} else {
// It doesn't exist
}
當然, existsSync
是同步和阻塞的。 雖然這有時很方便,但如果您需要並行執行其他操作(例如一次檢查多個文件的存在),您應該使用其他基於回調的方法之一。
現代版本的 Node 還支持基於 Promise 的fs
方法版本,人們可能更喜歡回調:
fs.promises.access(path)
.then(() => {
// It exists
})
.catch(() => {
// It doesn't exist
});
這是一個使用bluebird替換現有存在的解決方案。
var Promise = require("bluebird")
var fs = Promise.promisifyAll(require('fs'))
fs.existsAsync = function(path){
return fs.openAsync(path, "r").then(function(stats){
return true
}).catch(function(stats){
return false
})
}
fs.existsAsync("./index.js").then(function(exists){
console.log(exists) // true || false
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.