Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
2 answers
You can check if a file exists using the fs
module. Besides the methods already mentioned, you can use fs.stat(path[, options], callback)
[1].
It's also asynchronous, and the callback returns two arguments (err, stats)
.
import { stat } from "node:fs";
stat("/path/to/file.ext", (err, stats) => {
if (err) {
// Something happened; check err.code to get details
} else {
// File exists
}
});
0 comment threads
The following users marked this post as Works for me:
User | Comment | Date |
---|---|---|
philipp.classen | (no comment) | May 20, 2024 at 17:08 |
You can use existsSync
:
import { existsSync } from 'node:fs';
if (existsSync('/path/to/file')) {
console.log('Found');
} else {
console.log('Not found');
}
If you want to avoid blocking, you can also use access
. If you pass no arguments, it runs in fs.constants.F_OK
mode, which will test if the given file or directory is visible to the calling process:
import { access } from 'node:fs/promises';
try {
await access('/path/to/file');
console.log('Found');
} catch {
console.error('Not found');
}
Keep in mind that testing if a file exist and then opening it, is not recommended. Instead directly opening the file and handling errors is preferred (quoting the docs):
Using fsPromises.access() to check for the accessibility of a file before calling fsPromises.open() is not recommended. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible.
0 comment threads