0

I want to know if it's possible to write in a file in multiple rows.

I wrote this snippet:

var fs = require('fs');

for(var i=1; i<10; i++){
   fs.writeFile('helloworld.txt', i, function (err) {
    if (err) return console.log(err);
});

But I'm seeing only one row written in the file. How can I write in 10 rows with the for loop?*

3
  • 3
    Possible duplicate of How to append to a file in Node? Commented Mar 16, 2017 at 16:06
  • @JorgeFuentesGonzález it still write in an entire row Commented Mar 16, 2017 at 16:09
  • 1
    Linefeed problem then. Check my answer. Commented Mar 16, 2017 at 16:13

2 Answers 2

2

If you want to add multiple lines, you need to append the linefeed character:

var fs = require('fs');
var str = "";
for(var i=1; i<10; i++){
    str += i + "\r\n"; // Linefeed \r\n usually on Windows and \n only on Linux
}
// Only one filewrite, to optimize
fs.writeFile('helloworld.txt', str, function (err) {
    if (err) return console.log(err);
});

If you want to append it doing multiple filewrites because of reasons, you will also need the linefeed character.

var fs = require('fs');
for(var i=1; i<10; i++){
    fs.appendFile('helloworld.txt', i + "\r\n", function (err) {
        if (err) return console.log(err);
    });
}

Protip: The key here is the linefeed character/s.

Protip 2: Keep your indentation clean.

Sign up to request clarification or add additional context in comments.

Comments

1

I think this will help you

 var data= [{ link:"localhost",text:"hello world"}];
var stream = fs.createWriteStream(fileName);
    stream.once('open', function() {
      stream.write('Link, Text\n');
      data.forEach(function(row) {stream.write(row.link+','+row.text+'\n')});
      console.log("Please Check YourFile!")
      stream.end();
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.