在TypeScript中读取文件夹下的JSON数据,可以使用Node.js的fs模块来实现。以下是一个简单的示例代码:

import fs from 'fs';

const folderPath = './data'; // 文件夹路径

fs.readdir(folderPath, (err, files) => {
  if (err) {
    console.error('Error reading folder:', err);
    return;
  }

  files.forEach(file => {
    const filePath = `${folderPath}/${file}`;
    fs.readFile(filePath, 'utf-8', (err, data) => {
      if (err) {
        console.error('Error reading file:', err);
        return;
      }

      try {
        const jsonData = JSON.parse(data);
        console.log(jsonData);
      } catch (err) {
        console.error('Error parsing JSON:', err);
      }
    });
  });
});

在上述代码中,首先使用fs.readdir方法读取指定文件夹下的文件列表。然后,遍历每个文件,使用fs.readFile方法读取文件内容。读取到的文件内容是一个字符串,我们可以使用JSON.parse方法将其解析为JSON对象。最后,可以对解析后的JSON数据进行操作或打印。

请注意,上述代码使用了Node.js的fs模块,因此需要在运行代码之前确保已经安装了Node.js,并且在执行代码时需要运行在Node.js环境中


原文地址: https://www.cveoy.top/t/topic/h2xe 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录