写一个获取文件夹内容的JS代码
以下是一个获取文件夹内容的JS代码示例:
const fs = require('fs');
function getFolderContent(folderPath) {
try {
const files = fs.readdirSync(folderPath);
return files;
} catch (error) {
console.error('Error reading folder content:', error);
return [];
}
}
// 用法示例
const folderPath = './path/to/folder';
const folderContent = getFolderContent(folderPath);
console.log('Folder content:', folderContent);
这段代码使用Node.js的fs模块来读取文件夹的内容。getFolderContent函数接受一个文件夹路径作为参数,并使用fs.readdirSync方法同步地读取文件夹内容。如果读取文件夹内容出现错误,函数会打印错误信息并返回一个空数组。
使用示例中,可以将要读取的文件夹路径传递给getFolderContent函数,然后获取文件夹内容并打印到控制台。请注意替换./path/to/folder为实际的文件夹路径
原文地址: https://www.cveoy.top/t/topic/ihtA 著作权归作者所有。请勿转载和采集!