Reputation: 1622
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?*
Upvotes: 0
Views: 77
Reputation: 11809
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.
Upvotes: 2
Reputation: 66
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();
});
Upvotes: 1