I am getting strings from a text file in Javascript.
I just want to show a message whenever the user enters the wrong file name or invalid file name.
like this: console.log(“You input is invalid”);
My code to read my text file and transfer the data to my variable is as follow:
JavaScript
x
const fs = require('fs');
var strings = [];
strings = fs.readFileSync('abc.txt','utf8');
I don’t know how to check the existence of the file and put it in an if-else statement.
Advertisement
Answer
You can use existsSync
JavaScript
const fs = require('fs');
const filePath = './file.txt';
try {
if (fs.existsSync( filePath )) {
// TASK TO PERFORM IF FILE EXISTS
console.log("File exists.");
} else {
// TASK TO PERFORM IF FILE DOESN'T EXISTS
console.log("Your input is invalid");
}
} catch(err) {
console.error(err);
}