Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
Every file comes with a set of details that we can inspect using Node.
In particular, using the stat() method provided by the fs module.
Pass a file path; Node calls your callback with two arguments: an error (or null) and the file stats:
const fs = require('fs')
fs.stat('/Users/flavio/test.txt', (err, stats) => {
if (err) {
console.error(err)
return
}
// we have access to the file stats in `stats`
})
Node also provides a synchronous method that blocks until the stats are ready:
const fs = require('fs')
try {
const stats = fs.statSync('/Users/flavio/test.txt')
} catch (err) {
console.error(err)
}
The stats object contains file metadata. You can extract:
- whether it is a file or directory —
stats.isFile(),stats.isDirectory() - whether it is a symbolic link —
stats.isSymbolicLink() - size in bytes —
stats.size
Other methods are available; these are the ones you will use most often.
const fs = require('fs')
fs.stat('/Users/flavio/test.txt', (err, stats) => {
if (err) {
console.error(err)
return
}
stats.isFile() //true
stats.isDirectory() //false
stats.isSymbolicLink() //false
stats.size // 1024000 // = 1MB
})