You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从字符串获取值多次写入文本文件且每次换行不覆盖原有内容?

问题根因

你使用的fs.writeFile()方法默认采用覆盖写入模式,每次调用都会先清空目标文件的原有内容,再写入新内容。你在写入内容后添加\n仅能调整本次写入内容的格式,不会改变写入模式,因此无法实现追加效果。

解决方案

有两种常用的修改方式:

  • 方案1:直接使用fs.appendFile()方法,该方法默认就是追加写入模式,无需额外配置,修改后的代码如下:
const fs = require('fs')
const readline = require('readline-sync');
const userinput = readline.question(`test\n`);
fs.appendFile('Output.txt', userinput + "\n", (err) => {
    if (err) throw err;
})
  • 方案2:保留fs.writeFile(),在参数中指定追加模式的flag:
const fs = require('fs')
const readline = require('readline-sync');
const userinput = readline.question(`test\n`);
// flag值'a'是append的缩写,代表追加写入模式
fs.writeFile('Output.txt', userinput + "\n", { flag: 'a' }, (err) => {
    if (err) throw err;
})

内容的提问来源于stack exchange,提问作者Braketsss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 20:09:03