append file

204 views
Skip to first unread message

Mark Stone

unread,
Sep 30, 2011, 8:50:07 PM9/30/11
to nodejs
Here's my scenario:

I have some lines of text in a file we'll call "file1.xml".
I have some lines of text in a variable we'll call "newText".
I have some lines of text in a file we'll call "file2.xml".

I want to (over)write the contents of file1.xml to a file we'll call
"target.xml".
I then want to append the contents of newText to the end of
target.xml.
I then want to append the contents of file2.xml to the end of
target.xml.

All of the file and variable sizes are guaranteed to be modest (a few
dozen lines of 80 character text at most).

What's the best way to do this? I've spent a good part of the
afternoon reading up on various approaches to file append, and haven't
found anything suitable. I could do it the brute force way and read in
file1.xml, concat newText with that, read in file2.xml and concat it
onto the rest, then write the whole thing out to target.xml, but it
seems like there ought to be a more elegant solution.

-Mark Stone

Martin Cooper

unread,
Sep 30, 2011, 10:52:36 PM9/30/11
to nod...@googlegroups.com

I'd probably pipe the two files and write out the text in between.
Something (very) roughly like this:

var newText = "some new text",
ws = fs.createWriteStream("target.xml"),
rs = fs.createReadStream("file1.xml");
rs.pipe(ws, { end: false });
rs.on('end', function () {
ws.write(newText);
rs = fs.createReadStream("file2.xml");
rs.pipe(ws, { end: false });
rs.on('end', function () {
ws.end();
console.log("Done.");
});
});

Some error checking would be good, but that's the general idea.

--
Martin Cooper


> -Mark Stone
>
> --
> Job Board: http://jobs.nodejs.org/
> Posting guidelines: https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
> You received this message because you are subscribed to the Google
> Groups "nodejs" group.
> To post to this group, send email to nod...@googlegroups.com
> To unsubscribe from this group, send email to
> nodejs+un...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/nodejs?hl=en?hl=en
>

Mark Stone

unread,
Sep 30, 2011, 11:09:59 PM9/30/11
to nodejs
I like your approach, because its operating system independent, and
because streams will scale well larger file sizes. Here's what I came
up with as an alternative after I posted the question:

var fs = require('fs');
var sys = require('sys');
var newText = "Some new text\n";
var exec = require('child_process').exec;
function puts(error, stdout, stderr)
{
sys.puts(stdout);
}
fs.writeFile("./newText.xml", newText, function(error, file)
{
if (error)
{
console.log("Could not write newText.xml");
}
});
exec("cat file1.xml >target.xml; cat newText.xml >>target.xml; cat
file2.xml >>target.xml; rm newTest.xml", puts);
Reply all
Reply to author
Forward
0 new messages