- Using exists()
- File Statistics
- Using open()
- Using read()
- Using writeFile()
- Using close()
- Conclusion
File Statistics
In Node.js, you can use the stat() method to derive statistics about a file. It takes a path string and callback function as arguments. The callback function also takes a couple of arguments: the err object and an object containing the stats found for the file. The following example shows the use of the stat() method:
var fs = require("fs"); var path = "C:\\Python27\\ArcGIS10.2\\python.exe"; fs.stat(path, function(error, stats) { console.log(stats); });
The output yields the following results object:
{ dev: 0, mode: 33206, nlink: 1, uid: 0, gid: 0, rdev: 0, ino: 0, size: 26624, atime: Wed Nov 13 2013 08:34:12 GMT-0600 (Central Standard Time), mtime: Wed Apr 11 2012 00:31:54 GMT-0500 (Central Daylight Time), ctime: Wed Apr 11 2012 00:31:54 GMT-0500 (Central Daylight Time) }
Depending on the type of file or operating system you are using, the stats returned may differ from these. The following table summarizes the stats returned by the stat() method.
Property |
Description |
dev |
ID of the device containing the file. |
mode |
File protection. |
nlink |
Number of hard links to the file. |
uid |
User ID of the file’s owner. |
gid |
Group ID of the file’s owner. |
rdev |
Device ID if the file is a special file. |
blksize |
Block size for file system I/O. |
ino |
File inode number. An inode is a file system data structure that stores information about a file. |
size |
File total size in bytes. |
blocks |
Number of blocks allocated for the file. |
atime |
Date object representing the file’s last access time. |
mtime |
Date object representing the file’s last modification time. |
ctime |
Date object representing the last time the file’s inode was changed. |
There are more methods that check whether a path is pointing to a file or is a directory. The stats object returned from the callback function contains methods for finding this out:
var fs = require("fs"); var path = "C:\\Python27\\ArcGIS10.2\\python.exe"; fs.stat(path, function(error, stats) { console.log(stats.isFile()); console.log(stats.isDirectory()); console.log(stats.isBlockDevice()); console.log(stats.isCharacterDevice()); console.log(stats.isFIFO()); console.log(stats.isSocket()); });