Answer the question
In order to leave comments, you need to log in
Checking for file existence?
Hello. Can you please tell me how to check for the existence of a file?
const fsPromises = require('fs').promises;
if (await fsPromises.access(fullPath, fs.constants.R_OK))
await fsPromises.unlink(fullPath);
}
(node:10253) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, stat '/home/user/ProjectWeb/coffee-print-server/galleries/pictures/10'
try {
await fsPromises.unlink(fullPath);
} catch (err) { }
Answer the question
In order to leave comments, you need to log in
const fs = require('fs'); // or import fs from 'fs'; with esm / experimental modules
function isFileExists(path) {
return new Promise((resolve, reject) => {
fs.access(path, fs.constants.F_OK, err => {
if(!err) return resolve(true);
if(err.code === 'ENOENT') return resolve(false);
reject(err);
});
});
}
It turns out that, as it were, the check is meaningless, you can just wrapin the case of a simple unlink it is possible, for more complex logic it is better to check first
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question