英文:
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';
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论