check if file exist js code example
Example 1: node check if file exists
const fs = require("fs");
if (fs.existsSync(path)) {
}
Example 2: javascript check if file exists on server
function doesFileExist(urlToFile) {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', urlToFile, false);
xhr.send();
if (xhr.status == "404") {
return false;
} else {
return true;
}
}
Example 3: javascript file exists check
function doesFileExist(urlToFile) {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', urlToFile, false);
xhr.send();
return xhr.status !== 404;
}
Example 4: use node js to check if a json file exists
const fs = require('fs')
const path = './file.txt'
try {
if (fs.existsSync(path)) {
}
} catch(err) {
console.error(err)
}
Example 5: js check file exist
import fs from 'fs';
const path = './file.txt';
try {
if (fs.existsSync(path)) {
}
} catch(err) {
console.error(err);
}
Example 6: use node js to check if a json file exists
const fs = require('fs')
const path = './file.txt'
fs.access(path, fs.F_OK, (err) => {
if (err) {
console.error(err)
return
}
})