check given path is valid or not in nodejs
const fs = require('fs'); const path = '/path/to/your/file';
fs.access(path, fs.constants.F_OK, (err) => { if (err) { console.error('Path does not exist'); } else { console.log('Path exists'); } });
Explanation:
1. Import the file system module using require('fs')
and assign it to the variable fs
.
2. Define the path to the file or directory you want to check.
3. Use fs.access
to check if the given path exists or not. The method takes the path, a constant that represents the mode of the file system access, and a callback function.
4. Within the callback function, check if an error occurred. If there is no error, the path exists; otherwise, it does not.