1const fs = require("fs"); // Or `import fs from "fs";` with ESM
2if (fs.existsSync(path)) {
3 // Do something
4}
1const fs = require("fs"); // Or `import fs from "fs";` with ESM
2if (fs.existsSync(path)) {
3 // Do something
4}
5
1const fs = require('fs')
2// We will convert sync function into a promise function
3// so when is ready will provide the result without blocking.
4const exists = async (path) => {
5 return await new Promise((resolve) => {
6 resolve(fs.existsSync(path));
7 });
8};
9// If you have a file name samples on same root it will result true.
10exists('./samples.txt').then(res => console.log(res))
11console.log(`I'm not blocked as I'll show up on first`)
1const fs = require('fs');
2
3let file = '../path/to/chad_warden.mpeg';
4
5// async
6const fileExists = (file) => {
7 return new Promise((resolve) => {
8 fs.access(file, fs.constants.F_OK, (err) => {
9 err ? resolve(false) : resolve(true)
10 });
11 })
12}
13
14// sync
15const fileExistsSync = (file) => {
16 try {
17 fs.accessSync(file, fs.constants.R_OK | fs.constants.W_OK);
18 return true;
19 } catch (err) {
20 return false;
21 }
22}