Skip to content
Advertisement

How to check if my input file is valid and existed in Javascript?

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:

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

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);
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement