fs - Check synchronously if file/directory exists in Node.js - Stack Overflow
Current Answer
You can use fs.existsSync()
:
const fs = require("fs"); // Or `import fs from "fs";` with ESM
if (fs.existsSync(path)) {
// Do something
}
It was deprecated for several years, but no longer is. From the docs:
Note that
fs.exists()
is deprecated, butfs.existsSync()
is not. (The callback parameter tofs.exists()
accepts parameters that are inconsistent with other Node.js callbacks.fs.existsSync()
does not use a callback.)
You've specifically asked for a synchronous check, but if you can use an asynchronous check instead (usually best with I/O), use fs.promises.access
if you're using async
functions or fs.access
(since exists
is deprecated) if not:
In an async
function:
try {
await fs.promises.access("somefile");
// The check succeeded
} catch (error) {
// The check failed
}
Or with a callback:
fs.access("somefile", error => {
if (!error) {
// The check succeeded
} else {
// The check failed
}
});
Không có nhận xét nào:
Đăng nhận xét