You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求将指定PHP代码转为JavaScript并实现TXT转JSON功能

JavaScript 实现本地TXT文件合并与JSON转换

一、对应PHP的TXT文件合并功能(Node.js环境)

因为浏览器出于安全限制无法直接访问本地文件系统,所以咱们用Node.js来实现和你PHP代码一致的后端功能:读取texts目录下所有.txt文件,将内容追加写入result.txt。

步骤1:依赖准备

Node.js原生没有glob(用来匹配文件路径),所以先安装这个工具包:

npm install glob

步骤2:实现代码

const fs = require('fs').promises;
const path = require('path');
const glob = require('glob');

async function mergeTxtFiles() {
  // 匹配texts目录下所有txt文件
  const txtFiles = glob.sync(path.join(__dirname, 'texts', '*.txt'));
  const outputPath = path.join(__dirname, 'texts', 'result.txt');

  // 可选:如果希望每次运行都清空目标文件再写入,就保留这行;如果要像PHP那样一直追加,就删掉
  await fs.writeFile(outputPath, '', 'utf8');

  // 遍历每个文件,追加内容到result.txt(加换行避免内容连在一起)
  for (const file of txtFiles) {
    const content = await fs.readFile(file, 'utf8');
    await fs.appendFile(outputPath, content + '\n', 'utf8');
  }

  console.log('所有TXT文件已合并完成!');
}

// 执行函数并捕获错误
mergeTxtFiles().catch(err => console.error('合并出错:', err));

二、将TXT内容转换为JSON的实现

想要把TXT内容转成JSON,得先确定你想要的JSON结构——这里给你两种最常用的实现方式:

方式1:将所有TXT内容整理为数组(每个元素包含文件名和内容)

const fs = require('fs').promises;
const path = require('path');
const glob = require('glob');

async function txtToJson() {
  const txtFiles = glob.sync(path.join(__dirname, 'texts', '*.txt'));
  const jsonResult = [];

  for (const file of txtFiles) {
    const content = await fs.readFile(file, 'utf8');
    const fileName = path.basename(file); // 获取完整文件名,比如"note.txt"
    jsonResult.push({
      fileName: fileName,
      content: content.trim() // 去除内容首尾空白字符
    });
  }

  // 写入格式化后的JSON文件(第三个参数2是用来缩进排版,让JSON更易读)
  await fs.writeFile(
    path.join(__dirname, 'texts', 'result.json'),
    JSON.stringify(jsonResult, null, 2),
    'utf8'
  );
  console.log('TXT转JSON完成!');
}

txtToJson().catch(err => console.error('转换出错:', err));

方式2:以文件名(不带后缀)作为键,内容作为值的对象结构

const fs = require('fs').promises;
const path = require('path');
const glob = require('glob');

async function txtToJson() {
  const txtFiles = glob.sync(path.join(__dirname, 'texts', '*.txt'));
  const jsonResult = {};

  for (const file of txtFiles) {
    const content = await fs.readFile(file, 'utf8');
    const fileName = path.basename(file, '.txt'); // 获取不带后缀的文件名,比如"note"
    jsonResult[fileName] = content.trim();
  }

  await fs.writeFile(
    path.join(__dirname, 'texts', 'result.json'),
    JSON.stringify(jsonResult, null, 2),
    'utf8'
  );
  console.log('TXT转JSON完成!');
}

txtToJson().catch(err => console.error('转换出错:', err));

额外说明

  • 上面的代码都用了async/await处理异步操作,比传统回调写法更直观易读;
  • 如果你的TXT内容本身是结构化的(比如每行是键:值格式),可以在读取内容后再做进一步解析,把内容拆分成更精细的JSON字段。

内容的提问来源于stack exchange,提问作者Riyota Miyagi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:53:53