如何在调用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
的数据会立即写入文件,而在整个程序运行完毕之前,我的程序中没有数据写入文件。
答案 0 :(得分:0)