一、参数介绍
使用fs.stat方法获取文件信息需要传入文件路径和回调函数,回调函数的参数是fs.Stats对象。
fs.Stats对象包含文件的类型、大小、修改时间、最近访问时间等信息。
fs.stat(path, (err, stats) => {
// 处理文件信息
})
二、文件类型
通过fs.Stats对象的isFile、isDirectory、isSymbolicLink等方法可以判断文件的类型。
isFile方法返回布尔值,表示文件是否为普通文件;
isDirectory方法返回布尔值,表示文件是否为目录;
isSymbolicLink方法返回布尔值,表示文件是否为符号链接。
fs.stat(path, (err, stats) => {
if (err) throw err;
if (stats.isFile()) {
console.log('普通文件');
} else if (stats.isDirectory()) {
console.log('目录');
} else if (stats.isSymbolicLink()) {
console.log('符号链接');
}
})
三、文件大小
通过fs.Stats对象的size属性可以获取文件的大小,单位为字节。
fs.stat(path, (err, stats) => {
if (err) throw err;
console.log(`文件大小为${stats.size}字节`);
})
四、文件权限
通过fs.Stats对象的mode属性可以获取文件的权限,权限值为一个八进制数。
可以使用toString方法将八进制数转换为对应的文件权限字符串。
fs.stat(path, (err, stats) => {
if (err) throw err;
console.log(`文件权限为${stats.mode.toString(8)}`);
})
五、文件时间
通过fs.Stats对象的ctime、mtime、atime属性可以获取文件的创建时间、修改时间、最近访问时间。
这些属性返回的是Date对象,可以使用toLocaleString方法将其转换为字符串。
fs.stat(path, (err, stats) => {
if (err) throw err;
console.log(`文件创建时间为${stats.ctime.toLocaleString()}`);
console.log(`文件修改时间为${stats.mtime.toLocaleString()}`);
console.log(`文件最近访问时间为${stats.atime.toLocaleString()}`);
})
六、完整示例代码
const fs = require('fs');
const path = 'file.txt';
fs.stat(path, (err, stats) => {
if (err) throw err;
if (stats.isFile()) {
console.log('普通文件');
console.log(`文件大小为${stats.size}字节`);
console.log(`文件权限为${stats.mode.toString(8)}`);
console.log(`文件创建时间为${stats.ctime.toLocaleString()}`);
console.log(`文件修改时间为${stats.mtime.toLocaleString()}`);
console.log(`文件最近访问时间为${stats.atime.toLocaleString()}`);
} else if (stats.isDirectory()) {
console.log('目录');
} else if (stats.isSymbolicLink()) {
console.log('符号链接');
}
})
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/196155.html