以下是使用Node.js遍历文件夹并导入index.js的代码示例:
const fs = require('fs');
const path = require('path');
function importFolder(folderPath) {
// 读取文件夹中的所有文件和子文件夹
const files = fs.readdirSync(folderPath);
files.forEach(file => {
const filePath = path.join(folderPath, file);
const stats = fs.statSync(filePath);
if (stats.isDirectory()) {
// 如果是文件夹,则递归调用importFolder函数
importFolder(filePath);
} else if (file === 'index.js') {
// 如果是index.js文件,则导入它
require(filePath);
}
});
}
// 指定要遍历的文件夹路径
const folderPath = '/path/to/folder';
importFolder(folderPath);
以上代码将会遍历指定文件夹及其子文件夹中的所有文件。对于每个文件,如果是文件夹,则递归调用importFolder函数;如果是index.js文件,则使用require函数导入它。
请注意替换/path/to/folder
为实际的文件夹路径。