我有一个 txt 文件,然后我需要运行所有以数字 2 开头的行,然后将它们放入我正在使用 node.js 的数组中,这是迄今为止尝试过的方法。前 3 行始终是静态的,因此它们不会改变,我正在使用 readFileSync 将文件放入变量中。所以我使用 substr 并且已经归因于它们所属的前 3 行,问题是,以数字 2 开头的行对于每个文件都是随机的,一个有 10 个,另外 15 个,然后我不能使用 substr。这是我到目前为止得到的。import pathFile from './readDir.js'import { readFileSync } from 'fs' const files = pathFile() const read = () => { let a = [] for (let i = 0; i < files.length; i++) a.push(readFileSync(files[i],'utf-8')) return a } const pedido = read(); const header = { identifier: pedido[0].substr(1,15), distributorCNPJ: pedido[0].substr(16,15).trim(), processingDate: pedido[0].substr(31,8), processingHour: pedido[0].substr(39,8), industryCNPJ: pedido[0].substr(47,15).trim() }const invoice = { customerCNPJ: pedido[0].substr(65,15), invoiceNumber: pedido[0].substr(80,12).trim(), date: pedido[0].substr(92,8), orderType: pedido[0].substr(100,1), returnType: pedido[0].substr(101,1), comercialPointer: pedido[0].substr(102,5), customerInvoiceNumber: pedido[0].substr(107,15).trim(), //deadLine: pedido[0].substr(122,3), Nao utiliza agentCode: pedido[0].substr(122,4)} const deadLine = { code: pedido[0].substr(129,5), description: pedido[0].substr(135,30).trim(), numberQuotes: pedido[0].substr(136,3), discount: pedido[0].substr(39,8), industryCNPJ: pedido[0].substr(47,15).trim() }console.log(deadLine)
1 回答
哔哔one
TA贡献1854条经验 获得超8个赞
查看 split 函数将文本拆分为数组。
const { readFileSync } = require('fs')
const file = readFileSync('./PEDEMS_01260848000112_20200908124543.txt')
const txtFile = file.toString()
const allLines = txtFile.split('\n') // Create array with lines
const invoice = allLines.slice(0,3) // Top 3 lines
const cleanLines = allLines.slice(3, allLines.length) // Everything except top 3 lines
// Loop through the lines
cleanLines.forEach(line => {
const columns = line.split(' ') // Split again on columnns
const hasTwo = columns[0].substr(0,1) // Check the first number
if (hasTwo) {
// It started with 2, you can do something
console.log('do some magic')
}
})
添加回答
举报
0/150
提交
取消