首页 > 解决方案 > 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 上不起作用...如何解决?

标签: node.jsfilesystems

解决方案


您将遇到的一个问题是它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!');
    }
});

当然,您应该添加自己的变量定义并更改文件名。


推荐阅读