英文:
Altering file using readline in NodeJS results in blank file
问题
我需要在我的 postinstall
npm 脚本的一部分中以编程方式更改一个文件。
因此,我已经编写了一个实用程序来搜索一个字符串并注释掉代码行,但结果文件是空白的。
const fs = require('fs');
const path = require('path');
const readline = require('readline');
const filePath = path.join(process.cwd(), 'test.txt');
const readStream = fs.createReadStream(filePath);
const writeStream = fs.createWriteStream(filePath);
const rl = readline.createInterface({
input: readStream,
output: writeStream,
terminal: false
});
rl.on('line', (line) => {
console.log(line);
// check if the line contains the code I want to comment out
if (line.includes('test string')) {
line = '// ' + line;
}
writeStream.write(line + '\n');
});
rl.on('close', () => {
readStream.close();
writeStream.close();
});
我做错了什么?首先,我的控制台语句从未被记录,而且ReadStream对象报告了bytesRead: 0
,尽管文件的路径是正确的。
英文:
I need to programmatically alter a file as part of my postinstall
npm script.
As such, I've written a utility to search for a string and comment the line of code out, however the resulting file is blank.
const fs = require('fs');
const path = require('path');
const readline = require('readline');
const filePath = path.join(process.cwd(), 'test.txt');
const readStream = fs.createReadStream(filePath);
const writeStream = fs.createWriteStream(filePath);
const rl = readline.createInterface({
input: readStream,
output: writeStream,
terminal: false
});
rl.on('line', (line) => {
console.log(line);
// check if the line contains the code I want to comment out
if (line.includes('test string')) {
line = '// ' + line;
}
writeStream.write(line + '\n');
});
rl.on('close', () => {
readStream.close();
writeStream.close();
});
What am I doing wrong? My console statement is never logged for one and the ReadStream object reports bytesRead: 0
, although the path to the file is correct.
答案1
得分: 2
你的代码问题在于你设置写入流的方式。通过直接使用fs.createWriteStream(filePath)
,你实际上是在用空流覆盖文件的内容。这就是为什么你最终得到一个空文件的原因。
在这里你可以找到更多信息:
https://stackoverflow.com/questions/11995536/node-js-overwriting-a-file
英文:
The issue in your code lies in the way you're setting up the write stream. By using
fs.createWriteStream(filePath)
directly, you're essentially overwriting the contents of the file with an empty stream. This is why you end up with a blank file.
Here you can found more information
https://stackoverflow.com/questions/11995536/node-js-overwriting-a-file
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论