【问题标题】:node.js using fs.writeFile - how to force a New Line in a file (\n)?node.js 使用 fs.writeFile - 如何在文件中强制换行 (\n)?
【发布时间】:2018-11-08 15:36:55
【问题描述】:

我需要将数组写入文件,但我不知道如何强制换行。

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.js filesystems


【解决方案1】:

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

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

【讨论】:

  • 谢谢,我确实通过将整个数组合并为 JSON 格式并删除了一些 '\n' 来解决这个问题。 “// path.resolve 以独立于操作系统的方式组合文件路径” - 这很有趣,值得关注/提及。
猜你喜欢
  • 2019-02-11
  • 2018-06-23
  • 2015-09-02
  • 1970-01-01
  • 2014-01-23
  • 2020-01-04
  • 1970-01-01
  • 1970-01-01
  • 2020-03-03
相关资源
最近更新 更多