Node.js WriteStream doesn't write data to file until closed

痞子三分冷 提交于 2019-12-24 02:52:45

问题


How can I cause the data to be written to the file as WriteStream.write() is called?

Edit: As it turns out, this works when I use the REPL and call the function. However, this doesn't work in my program:

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);

It should be noted that word.generatePermutations is an extremely intensive function and often can take several minutes (sometimes over an hour) to return. My issue is that the data it returns should be written to the output file immediately so that the entire program doesn't need to finish running for the results to be read. Hopefully someone can make sense of all this.

To clarify, data written to a WriteStream in the REPL is immediately written to the file, while no data is written to the file in my program until the entire program finishes running.


回答1:


Try these packages:

https://www.npmjs.com/package/flushwritable

https://www.npmjs.com/package/flush-write-stream

And I think you question is duplicate of How to flush Node.js file writeStream properly?



来源:https://stackoverflow.com/questions/48410361/node-js-writestream-doesnt-write-data-to-file-until-closed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!