Node.js中的fs.readdir()方法用于读取指定目录中的文件和子目录。但是该方法不会返回文件的扩展名。
要获取文件扩展名,可以使用Node.js内置的path模块来处理文件路径。使用path.extname()方法可以从文件路径中提取出文件的扩展名。
下面是一个示例代码,演示如何使用fs.readdir()和path.extname()来获取文件扩展名:
const fs = require('fs');
const path = require('path');
const directoryPath = '/path/to/directory';
fs.readdir(directoryPath, (err, files) => {
if (err) {
console.error('Error reading directory:', err);
return;
}
files.forEach(file => {
const filePath = path.join(directoryPath, file);
const ext = path.extname(filePath);
console.log('File:', file);
console.log('Extension:', ext);
});
});
上述代码中,首先使用fs.readdir()方法读取指定目录中的文件列表。然后,通过forEach循环遍历每个文件,使用path.join()方法构建文件的完整路径。最后,使用path.extname()方法获取文件的扩展名,然后输出到控制台。
请注意,以上代码中的/path/to/directory
应替换为实际的目录路径。此外,你还可以根据需要对路径进行进一步处理,例如判断文件是否具有特定扩展名或将文件进行分类。
关于Node.js的fs、path模块的更多详细信息,以及对应的腾讯云产品,请参考以下链接:
希望以上信息能够对你有所帮助!如有更多问题,请随时提问。
领取专属 10元无门槛券
手把手带您无忧上云