DEV Community

SemihGKL
SemihGKL

Posted on

How to test the existence of a file in Javascript

How to test the existence of a file in Javascript

Table of contents

  1. Create a file
  2. The file testing function
  3. Execute code
  4. Tips

1 - Create a file

First, we need to create another file that contains our test function.
You can create this file using the IDE of your choice or by typing the following command in the terminal :

touch testFile.js
Enter fullscreen mode Exit fullscreen mode

2 - The file testing function

In the previous file, add this function that takes an array as an argument. For each file name in the array, we will test its existence.

function isNotFile(args) {
    for (let i = 0; i < args.length; i++) {
        if (fs.existsSync(args[i]) == true) {
            console.log(args[i] + "this file exist")
        } else {
            console.log(args[i] + "this file doesn't exist")
        }
    }
    return true
}
Enter fullscreen mode Exit fullscreen mode

Now, we need to call the function with the correct parameter (don't forget the array):

isNotFile(['test.txt'])
Enter fullscreen mode Exit fullscreen mode

3 - Execute code

Now, all you need to do is create the 'test.txt' file. To do this, run the following command in the terminal:

touch test.js
Enter fullscreen mode Exit fullscreen mode

And now, simply execute our function in the terminal:

node testFile.js
Enter fullscreen mode Exit fullscreen mode

If you have successfully created the 'test.txt' file, you should receive a message indicating that the file exists in the terminal.


4 - Tips

The best way to utilize this code is to check out my topic, "Javascript in the Terminal". There, you will learn and see how to retrieve the arguments passed in the terminal command, such as:

node testFile.js test.js test2.js
Enter fullscreen mode Exit fullscreen mode

Practice makes progress ! 💪

~SemihGKl

Top comments (0)