【问题标题】:Is there a way to Read and Write the same line in a NodeJS file stream?有没有办法在 NodeJS 文件流中读取和写入同一行?
【发布时间】:2019-07-22 08:46:44
【问题描述】:

对于节点生成器项目,我想在函数不存在时将单词 export 放在函数前面。现在我使用了 line-reader 包,因为它使用干净。我不认为这个包提供了读取和写入同一行并将其保存到同一文件的选项。现在我正在寻找建议或帮助如何为同一行实现读取和写入流,或者是创建两个不同流的唯一选择?

所以我想要完成的是当上面的行包含生成时,下一行不包含条件导出。应将导出添加到行首。

import fs from 'fs';
import lineReader from 'line-reader';

const curFile : string = 'currentFile.ts'
let nextLine: boolean = false;

lineReader.eachLine(curFile, async (line: string, last: boolean | undefined): Promise<void> => {
    if (nextLine) {
        if(!line.includes('export')){
            const writeStream = fs.createWriteStream(curFile, {
                encoding: 'utf8',
                autoClose: true,
            });
            await writeStream.write(`export ${line}`);
            writeStream.end();
        }
        nextLine = false;
    }

    if (line.includes('generate')) {
        nextLine = true;
    }
});


【问题讨论】:

    标签: node.js fs


    【解决方案1】:

    我是这样解决的:

    import fs from 'fs';
    import lineReader from 'line-reader';
    
    const curFile: string = 'currentFile.ts';
    const secFile: string = 'otherFile2.ts'
    let nextLine: boolean = false;
    
    const writeStream = fs.createWriteStream(secFile, {
        encoding: 'utf8',
        autoClose: true,
    });
    lineReader.eachLine(
        curFile,
        async (line: string, last: boolean | undefined): Promise<void> => {
            if (nextLine) {
                if (!line.includes('export')) {
                    writeStream.write(`export ${line}`);
                } else {
                    writeStream.write(`${line}`);
                }
                nextLine = false;
            }
    
            // check if line includes generate
            if (line.includes('generate')) {
                nextLine = true;
            }
    
            // If the last rule has been reached end stream and remove original file and replace it with the sec file.
            if (last) {
                writeStream.end();
                replaceOriginalFile(curFile, secFile)
            }
        },
    );
    
    
    function replaceOriginalFile(originalPath: string, newPath: string) {
        // remove original file
        fs.unlinkSync(originalPath);
        // rename file to replace original
        fs.rename(newPath, originalPath, function(err) {
            if (err) throw err;
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2016-02-11
      • 1970-01-01
      • 1970-01-01
      • 2014-06-04
      • 1970-01-01
      • 1970-01-01
      • 2021-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多