Another common task is to get basic information about file system objects, such as file size, mode, modification time, whether the entry is a file or folder, etc. You can obtain such information by using one of the following calls:
fs.stat(path, callback)
fs.statSync(path)
The fsStatSync()
method returns a Stats
object. The fs.stat()
method is executed, and the Stats
object is passed to the callback function as the second parameter. The first parameter is error
if an error occurs.
Table 6.2 lists some of the most commonly used attributes and methods attached to the Stats
object.
The code in Listing 6.9 illustrates the use of the fs.stat()
call by making the call, then outputting the results of the object as a JSON string and using the isFile()
, isDirector()
, and isSocket()
calls, as shown in the output in Figure 6.9.
01 var fs = require('fs'),
02 fs.stat('file_stats.js', function (err, stats) {
03 if (!err){
04 console.log('stats: ' + JSON.stringify(stats, null, ' '));
05 console.log(stats.isFile() ? "Is a File" : "Is not a File");
06 console.log(stats.isDirectory() ? "Is a Folder" : "Is not a Folder");
07 console.log(stats.isSocket() ? "Is a Socket" : "Is not a Socket");
08 stats.isDirectory();
09 stats.isBlockDevice();
10 stats.isCharacterDevice();
11 //stats.isSymbolicLink(); //only lstat
12 stats.isFIFO();
13 stats.isSocket();
14 }
15 });