56 lines
1.4 KiB
JavaScript
56 lines
1.4 KiB
JavaScript
|
const fs = require('node:fs')
|
||
|
const path = require('node:path')
|
||
|
|
||
|
// 读取文件路径
|
||
|
const filePath = path.join(__dirname, 'jdyx.txt')
|
||
|
|
||
|
// 输出文件路径
|
||
|
const outputFilePath = path.join(__dirname, 'output.json')
|
||
|
|
||
|
// 读取文件内容
|
||
|
fs.readFile(filePath, 'utf8', (err, data) => {
|
||
|
if (err) {
|
||
|
console.error('读取文件失败:', err)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
const records = []
|
||
|
let currentRecord = ''
|
||
|
let capturing = false // 是否正在捕获一条记录
|
||
|
|
||
|
// 按字符处理数据
|
||
|
for (let i = 0; i < data.length; i++) {
|
||
|
const char = data[i]
|
||
|
|
||
|
// 检查是否找到 `als`
|
||
|
if (!capturing && data.slice(i, i + 3) === 'als') {
|
||
|
capturing = true // 开始捕获
|
||
|
currentRecord = 'als' // 初始化记录
|
||
|
i += 2 // 跳过已匹配的 "als"
|
||
|
continue
|
||
|
}
|
||
|
|
||
|
// 捕获状态下,遇到空格时结束记录
|
||
|
if (capturing) {
|
||
|
if (char === ' ') {
|
||
|
records.push(currentRecord) // 保存当前记录
|
||
|
capturing = false // 停止捕获
|
||
|
currentRecord = '' // 重置记录
|
||
|
}
|
||
|
else {
|
||
|
currentRecord += char // 继续捕获字符
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// 将结果写入到JSON文件中
|
||
|
fs.writeFile(outputFilePath, JSON.stringify(records, null, 2), (err) => {
|
||
|
if (err) {
|
||
|
console.error('写入文件失败:', err)
|
||
|
}
|
||
|
else {
|
||
|
console.log(`记录已保存到文件: ${outputFilePath}`)
|
||
|
}
|
||
|
})
|
||
|
})
|