node.js - node.js 使用 fs.writeFile - 如何在文件中强制换行 (\n)?
问题描述
我需要将数组写入文件,但我不知道如何强制换行。
var arr = [1,2,a,b,{c:d},[x,y,z],1a]; // some array
for (var i=0; i<=arr; i++)
{
arr[i] = arr[i] + "\n";
}
要不就:
arr.split(",").join("\n");
不起作用。
我只想在新行显示文件中的每个数组索引元素。
在记事本中,我只看到所有 '1\n'、'a\n' 等。我听说这是因为 Windows 使用的是 '\r\n' 而不是 '\n' 但我想这在 linux 上不起作用...如何解决?
解决方案
您将遇到的一个问题是它1a
不是 JavaScript 中的有效标记 - 如果您想将其用作纯文本字符串,则必须将其放在引号中。除此之外,试试这个:
// Import node's filesystem tools
const fs = require('fs');
const path = require('path');
// variable definitions
const a = 1;
const b = 'hello';
const d = 'text';
const x = 0;
const y = [];
const z = 'hi'
const arr = [1, 2, a, b, {c: d}, [x, y, z], '1a']
// reduce goes through the array and adds every element together from start to finish
// using the function you provide
const filedata = arr.reduce((a, b) => {
// manually convert element to string if it is an object
a = a instanceof Object ? JSON.stringify(a) : a;
b = b instanceof Object ? JSON.stringify(b) : b;
return a + '\r\n' + b;
});
// path.resolve combines file paths in an OS-independent way
// __dirname is the directory of the current .js file
const filepath = path.resolve(__dirname, 'filename.txt');
fs.writeFile(filepath, filedata, (err) => {
// this code runs after the file is written
if(err) {
console.log(err);
} else {
console.log('File successfully written!');
}
});
当然,您应该添加自己的变量定义并更改文件名。
推荐阅读
- vhdl - 不理解 numeric_std to_unsigned 函数调用的错误消息,选定的信号分配
- api - 从管道本身取消 Synapse 管道
- liferay - 工作流删除操作
- mqtt - 连接后 Mqtt 客户端立即断开连接
- api - 隧道 IP 地址
- sql-server - Microsoft SQL Server:在大厅数据库中查找和更新确切值,即使它是 PRIMARY
- reactjs - React Router 卡在某条路线上
- elasticsearch - 如何使用 NEST (C#) 覆盖弹性中的扁平类型参数
- windows - 通过 BLE 将 Lopy 与 Windows 连接
- vue.js - 尝试在 VueJs 中禁用导航按钮时出错