【问题标题】:Node.js WriteStream doesn't write data to file until closedNode.js WriteStream 在关闭之前不会将数据写入文件
【发布时间】:2018-07-02 18:47:29
【问题描述】:

如何在调用WriteStream.write() 时将数据写入文件?

编辑: 事实证明,这在我使用 REPL 并调用该函数时有效。但是,这在我的程序中不起作用:

import * as FS from "fs";
import { LetterGroup } from "./LetterGroup";
import { Dictionary } from "./Dictionary";
import { Word } from "./Word";
import * as OS from "os";

const groups: Array<LetterGroup> = LetterGroup.letterGroupsFromString(FS.readFileSync("./letterGroups.txt").toString());
const dictionary = Dictionary.create(FS.readFileSync("./dictionary.txt").toString());

const inputStr: string = FS.readFileSync("./input.txt").toString();
const inputWords = new Array<Word>();
const fileStream = FS.createWriteStream("./output.txt");

for (const line of inputStr.trim().split(OS.EOL))
{
    inputWords.push(new Word(line));
}

function permute(index: number)
{
    index = Math.floor(index);

    if (!(index >= 0 && index < inputWords.length))
    {
        return;
    }

    const word: Word = inputWords[index];

    let outputString: string = "";

    outputString += `Valid permutations of '${word.wordString}':` + OS.EOL;

    console.log(`Testing '${ word.wordString }'...`);

    for (const permutation of word.generatePermutations(groups, dictionary, true))
    {
        outputString += permutation.wordString + OS.EOL;
    }

    outputString += OS.EOL;
    console.log();

    if (!fileStream.write(outputString))
    {
        console.log("Wrote to file too fast! Will resume writing once the system catches up...");
        fileStream.once("drain", () => permute(index));
        return;
    }

    permute(index + 1);
}

permute(0);

需要注意的是,word.generatePermutations 是一个非常密集的函数,通常需要几分钟(有时超过一个小时)才能返回。我的问题是它返回的数据应该立即写入输出文件,这样整个程序就不需要完成运行来读取结果。希望有人能理解这一切。

为了澄清,在 REPL 中写入 WriteStream 的数据会立即写入文件,而在我的程序中,直到整个程序完成运行,才会将数据写入文件。

【问题讨论】:

  • Writing files in Node.js的可能重复
  • @CDspace 我实际上决定使用文件描述符和fs.write() 来解决问题,但这并不能改变我最初的问题没有得到回答的事实。我特别想知道是否有办法让 WriteStream 在将数据写入磁盘时将其数据同步到磁盘。这似乎在 REPL 中有效,但在我的程序中无效。我将编辑原始问题。
  • 我这里也有同样的问题。找到解决方案了吗?

标签: node.js file fs


【解决方案1】:

【讨论】:

  • 我会检查这些包,但你建议的线程与我的不同,因为他试图在关闭流后刷新文件,而我想在流处于活动状态时刷新文件.
猜你喜欢
  • 2017-09-19
  • 2019-07-22
  • 2019-04-16
  • 2018-07-04
  • 2017-03-21
  • 2018-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多