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:
xxxxxxxxxx
1
const fs = require('fs');
2
3
const status = fs.lstatSync('/path/to/somewhere');
4
5
if (status.isFile()) {
6
// ...
7
}
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.
Projects structure:
xxxxxxxxxx
1
Project/
2
|
3
+-- my_directory/
4
| |
5
| +-- my_file.json
6
|
7
+-- my_script.js
Example my_script.js
file:
xxxxxxxxxx
1
const fs = require('fs');
2
3
const isFile = (path) => {
4
const status = fs.lstatSync(path);
5
return status.isFile();
6
};
7
8
9
// Usage example:
10
11
console.log(isFile('my_directory')); // false
12
console.log(isFile('my_directory/my_file.txt')); // true
- callbacks based example
- async/await based example