yasiDrovi
yasiDrovi

Reputation: 137

node.js using fs.writeFile - how to force a New Line in a file (\n)?

I need to write array to a file, and I don't know how to force a New Line.

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";
}

or just:

arr.split(",").join("\n");

doesn't work.

I just want to dispaly every array index element in a file at a new line.

In a notepad I simply see all '1\n', 'a\n', etc. I heard it's because windows is using '\r\n' instead of '\n' but I guess this will not work on linux then... How to resolve that?

Upvotes: 1

Views: 3983

Answers (1)

timmcca-be
timmcca-be

Reputation: 188

One issue you'll have is that 1a is not a valid token in JavaScript - if you want to use it as a plain text string, you'll have to put it in quotes. Other than that, try this:

// 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!');
    }
});

Of course, you should add your own variable definitions and change the file name.

Upvotes: 1

Related Questions