B
B
Bogdan2019-05-20 15:57:13
Node.js
Bogdan, 2019-05-20 15:57:13

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);
}

I am getting an error:
(node:10253) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, stat '/home/user/ProjectWeb/coffee-print-server/galleries/pictures/10'

It turns out that, as it were, the check is meaningless, you can just wrap
try {
      await fsPromises.unlink(fullPath);
    } catch (err) { }

Or how to do it right?
Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2019-05-20
@bogdan_uman

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 wrap
in the case of a simple unlink it is possible, for more complex logic it is better to check first

H
hzzzzl, 2019-05-20
@hzzzzl

This?
https://nodejs.org/api/fs.html#fs_fs_existssync_path

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question