在Node.js中为文件输出添加换行字符。

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

Adding newline characters in Node.js for file output

问题

我正在开发一个Node.js应用程序,需要以一种有效且被各种文本编辑器和工具(特别是.bib文件)识别的方式向文件添加换行字符。

我尝试在每个字段后面添加\n。以下是一个示例:

const data = '这是一些文本,我想要在后面添加一个新行';
const newline = '\n';

res.setHeader('Content-Type', 'text/x-bibtex;charset=utf-8');
res.setHeader('Content-Disposition', `attachment;filename=${filename}`);
res.send(data);

然而,当我在文本编辑器中打开文件时,似乎无法识别换行字符,所有内容都显示在同一行上。

英文:

I'm working on a Node.js application and need to append newline characters to a file in a way that is valid and recognized by various text editors and tools(Specific for .bib files).

I tried to add \n after each field. This is one case.

const data = 'This is some text that I want to append with a new line';
const newline = '\n';

res.setHeader('Content-Type', 'text/x-bibtex;charset=utf-8');
res.setHeader('Content-Disposition', `attachment;filename=${filename}`);
res.send(data);

However, when I open the file in a text editor, the newline character doesn't seem to be recognized, and everything appears on a single line.

答案1

得分: 1

你可以使用内置的 os 模块。
它在各种文本编辑器和工具中都是有效的并得到认可,你需要根据操作系统的惯例使用适当的换行序列。

const os = require('os');
const newline = os.EOL;
fs.appendFileSync(filePath, `${data}${newline}`, { encoding: 'utf8' });
英文:

You can use the built in os module.
Its valid and recognized by various text editors and tools, you need to use the appropriate newline sequence based on the operating system's conventions

const os = require('os');
const newline = os.EOL;
fs.appendFileSync(filePath, `${data}${newline}`, { encoding: 'utf8' });

答案2

得分: 0

我刚才在做某种类型的

const data = '这是一些我想要附加新行的文本'.trim().replace();

所以我只需在replace方法后添加'/n/':

const data = '这是一些我想要附加新行的文本'.trim().replace() + '/n';
英文:

I was doing some sort of

const data = 'This is some text that I want to append with a new line'.trim().replace();

So I just add '/n/ after replace method :

const data = 'This is some text that I want to append with a new line'.trim().replace()+ '/n';

huangapple
  • 本文由 发表于 2023年6月27日 19:22:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76564351.html
匿名

发表评论

匿名网友

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

确定