我需要将数组写入文件,但我不知道如何强制换行。
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!');
}
});
当然,您应该添加自己的变量定义并更改文件名。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句