Introduction:
In our previous blogs, we are familiar with what precisely Node.js is. In this article, we are concerned about how we can apply node.js file stats and node.js paths.
Though their name is taken together, how they part their ways, let’s figure this out in detail.
Source: giphy
Node.js File stats:
Every file has a bunch of details that can be reviewed by Node.js. Generally, the stat() method is used provided by the fs module.
It is called, passing a file path and once the file details are caught by the Node.js, it will call the callback function passed. It accepts two arguments: an error message and file stats.
const fs = require('fs') fs.stat('/User/codingNinja/practise.txt', (eror, stats) => { if (eror) { console.error(eror) return } // Accessing file stats in `stats`. }) |
A sync method is also provided by node.js. This method blocks all threads until and unless the file stats are ready.
const fs = require('fs') try { const stats = fs.statSync('/User/codingNinja/practise.txt') } catch (err) { console.error(err) } |
We know the file information is contained in the stats variable. Now, the question is what kind of information can be extracted using these stats.
The following things is contained in the stats:
- If the file is a directory or a file, then prefer stats.isFile() and stats.isDirectory().
- If the file is a symbolic link, then prefer stats.isSymbolicLink().
- For the files in bytes, stats. size.
const fs = require('fs') fs.stat('/User/codingNinja/practise.txt', (err, stats) => { if (err) { console.error(err) return } stats.isFile() // True. stats.isDirectory() // False. stats.isSymbolicLink() // False. stats.size // 1024000 = 1MB. }) |
Now that we are comfortable with file stats in node.js. Let’s move forward towards the paths in node.js.