rwallace
rwallace

Reputation: 33395

Node.js equivalent of fopen/fprintf

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?

Upvotes: 3

Views: 5290

Answers (1)

robertklep
robertklep

Reputation: 203304

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

Upvotes: 7

Related Questions