3

I'm trying to write a text file from node.js where the contents will be calculated line by line so building a string for writing in one shot would take quadratic time, and writing line by line seems the best option.

Basically I'm trying to do something along the lines of:

FILE *f = fopen("foo.txt", "w");
for (int i = 0; i < 100; i++)
    fprintf(f, "line %d\n", i);

What's the node.js equivalent?

rwallace
  • 31,405
  • 40
  • 123
  • 242
  • 1
    Did you see `fs.createWriteStream`? http://nodejs.org/api/fs.html#fs_fs_createwritestream_path_options – Dogbert Jun 05 '13 at 10:54
  • @Dogbert I did, but wasn't clear from the documentation and a couple of Google searches whether this is what it was meant for. Is it the preferred facility for this sort of use case? Are there examples anywhere of its use in simple 'write a text file' mode? – rwallace Jun 05 '13 at 11:04
  • I flag this as duplicate of: http://stackoverflow.com/questions/2496710/nodejs-write-to-file – Eloims Jun 05 '13 at 11:14

1 Answers1

7

This code functions pretty much similar to your C code:

var fs    = require('fs');
var util  = require('util');

fs.open('foo.txt', 'w', function(err, fd) {
  for (var i = 0; i < 100; i++)
    fs.write(fd, util.format('line %d\n', i));
  fs.close(fd);
});
robertklep
  • 198,204
  • 35
  • 394
  • 381