node读取文件夹下所有文件

const fs = require('fs');
const path = require('path');

const express = require('express');
const app = express();

app.get('/dirStructure', (req, res) => {
  const dir = req.query.dir;
  if (!dir) {
    res.status(400).send('目录不能为空!');
    return;
  }

  const dirPath = path.join(__dirname, dir);
  if (!fs.existsSync(dirPath)) {
    res.status(404).send('目录不存在!');
    return;
  }

  const structure = getDirStructure(dirPath);
  res.send(structure);
});

function getDirStructure(dirPath) {
  const files = fs.readdirSync(dirPath);
  const dirs = [];
  const structure = {
    name: path.basename(dirPath),
    type: 'dir',
    children: []
  };
  
  files.forEach(file => {
    const filePath = path.join(dirPath, file);
    const stat = fs.statSync(filePath);

    if (stat.isDirectory()) {
      const dirStructure = getDirStructure(filePath);
      dirs.push(dirStructure);
    } else {
      structure.children.push({
        name: file,
        type: 'file'
      });
    }
  });

  structure.children = structure.children.concat(dirs);
  return structure; 
}

app.listen(3000);

# 使用或者自行进行打包

npm install express
node index.js

# 前端调用:

import axios from 'axios';

let config = {
  method: 'get',
  maxBodyLength: Infinity,
  url: 'http://localhost:3000/dirStructure?dir=ot/src',
  headers: { 
    'content-type': 'application/json'
  }
};

axios.request(config)
.then((response) => {
  console.log(response.data);
})
.catch((error) => {
  console.log(error);
});

这个服务定义了/dirStructure接口,可以传入dir查询参数指定目录,并返回该目录的完整目录结构。 主要逻辑在getDirStructure()函数中,它会递归遍历传入的目录,构建目录树结构。对每个文件,会判断是文件还是目录,并添加到树结构中。 所以,如果我们请求/dirStructure?dir=somedir,会返回somedir目录的详细目录树结构,包含所有子文件夹和文件。

也可以/dirStructure?dir=somedir/a/b,会返回somedir/a/b目录的详细目录树结构,包含所有子文件夹和文件。

lastUpdate: 6/1/2023, 2:30:01 PM