对于节点生成器项目,我想将单词export放在不存在的函数前面。现在,我使用了软件包line-reader,因为它的用法很干净。我认为该程序包不提供读写同一行并将其保存到同一文件的选项。现在,我正在寻找建议或帮助,以了解如何在同一行中实现读写流,或者是创建两个不同流的唯一选择?
所以我要完成的是,当上面的行包含generate时,下一行不包含条件导出。导出应添加到该行的开头。
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;
}
});
答案 0 :(得分:0)
我这样解决了:
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;
});
}