EN
Node.js - check if path is file
3
points
In this article, we would like to show you how to check if path is a file using Node.js.
Quick solution:
const fs = require('fs');
const status = fs.lstatSync('/path/to/somewhere');
if (status.isFile()) {
// ...
}
Warning:
When
/path/to/somewhere
is soft link and indicates to non-existing path, it is necessary to callfs.existsSync(/path/to/somewhere)
before status checking.
Practical example
Projects structure:
Project/
|
+-- my_directory/
| |
| +-- my_file.json
|
+-- my_script.js
Example my_script.js
file:
const fs = require('fs');
const isFile = (path) => {
const status = fs.lstatSync(path);
return status.isFile();
};
// Usage example:
console.log(isFile('my_directory')); // false
console.log(isFile('my_directory/my_file.txt')); // true
TODO
- callbacks based example
- async/await based example