我怎样才能将数据写入文件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
是一个极其密集的函数,通常需要几分钟(有时超过一个小时)才能返回。我的问题是,它返回的数据应该立即写入输出文件,这样整个程序就不需要完成运行才能读取结果。希望有人能够理解这一切。
为了澄清,数据写入WriteStream
REPL中的数据会立即写入文件,而我的程序中则直到整个程序运行完毕才将数据写入文件。
尝试这些包:
https://www.npmjs.com/package/flushwritable https://www.npmjs.com/package/flushwritable
https://www.npmjs.com/package/flush-write-stream https://www.npmjs.com/package/flush-write-stream
我认为你的问题是重复的如何正确刷新 Node.js 文件 writeStream? https://stackoverflow.com/questions/14639388/how-to-flush-node-js-file-writestream-properly
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)