Node Folder or file exists
To check if a folder or file exists in Node.js, you can follow these steps:
- Import the
fs
module:
const fs = require('fs');
The fs
module in Node.js provides file system-related functionality.
- Use the
fs.existsSync()
method:
const path = 'path/to/folder_or_file';
const exists = fs.existsSync(path);
The fs.existsSync()
method checks if a given path exists in the file system. It returns true
if the path exists, and false
otherwise. You need to provide the path to the folder or file you want to check in the path
variable.
- Handle the result:
if (exists) {
console.log('Folder or file exists.');
} else {
console.log('Folder or file does not exist.');
}
Based on the result of fs.existsSync()
, you can handle the existence or non-existence of the folder or file. In this example, it simply logs a message indicating whether the folder or file exists or not.
That's it! By following these steps, you can check if a folder or file exists in Node.js. Remember to replace 'path/to/folder_or_file'
with the actual path you want to check.