使用NodeJS中的readline更改文件会导致文件为空。

huangapple go评论72阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年7月13日 21:42:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76680072.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定