javascript - Node.js equivalent of fopenfprintf - Stack Overflow

I'm trying to write a text file from node.js where the contents will be calculated line by line so

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?

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?

Share Improve this question asked Jun 5, 2013 at 10:52 rwallacerwallace 33.7k44 gold badges134 silver badges281 bronze badges 3
  • 1 Did you see fs.createWriteStream? nodejs/api/fs.html#fs_fs_createwritestream_path_options – Dogbert Commented Jun 5, 2013 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 Commented Jun 5, 2013 at 11:04
  • I flag this as duplicate of: stackoverflow./questions/2496710/nodejs-write-to-file – Eloims Commented Jun 5, 2013 at 11:14
Add a ment  | 

1 Answer 1

Reset to default 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);
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744386626a4571696.html

相关推荐

  • javascript - Node.js equivalent of fopenfprintf - Stack Overflow

    I'm trying to write a text file from node.js where the contents will be calculated line by line so

    7天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信