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
1 Answer
Reset to default 7This 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
评论列表(0条)