NodeJS - 如何在不读取所有行的情况下删除文本文件的第一行?

NodeJS - How to remove the first line of a text file without read all lines?

我在 S3 存储桶中有以下文件:

field1;field2;field3
VAL11,VAL12;VAL13
VAL21,VAL22;VAL23
VAL31,VAL32;VAL33

最终目标是只删除文件的第一行field1;field2;field3。这是期望的结果:

VAL11,VAL12;VAL13
VAL21,VAL22;VAL23
VAL31,VAL32;VAL33

目前我有以下功能,它正在读取文件中的所有内容。并使用 \n 进行分解,删除第一行,然后使用 \n.

再次连接所有行

那么有没有办法在不分解并重新组装的情况下删除第一行?

async function createRef (version,FIRMWARE_BUCKET_NAME) {
    const refFile = version + '/ref.ref'
    const ref = await getObject(FIRMWARE_BUCKET_NAME, refFile)
    const refString = ref.toString('utf8')
    let arrRef = refString.split('\n')
    arrRef.shift()
    
    let refConcatenated=''
    for (let i = 0; i < arrRef.length; i++) {
        if (arrRef[i] !== '' ) {
            let line = arrRef[i]
            refConcatenated = refConcatenated + line + '\n'
        }
    }
    return refConcatenated
}

它是 not possible to remove one line without re-reading and writing the whole file in some way — you can replace lines as in , or use streaming to avoid needing to read the whole file into memory as in this answer. If you wanted to truncate the file you could use fs.truncate,但这对您删除 first 行没有帮助。您至少可以通过使用 .join('\n') 而不是循环来简化函数的最后一部分。