Just testing NodeJS out and still learning to think in javascript, how can I get this basic FileIO operation below to work?
Here’s what I’d like it to do:
- Read XML file (read into memory)
- Put all contents into a variable
- Write XML file from variable
- Output should be the same as original file
var fs = require('fs');
var filepath = 'c:\/testin.xml';
fs.readFile(filepath, 'utf8', function(err, data) {
if(err) {
console.error("Could not open file: %s", err);
}
});
fs.writeFile('c:\/testout.xml', data, function(err) {
if(err) {
console.error("Could not write file: %s", err);
}
});
The problem with your code is that you try to write the data you read to the target file before it has been read – those operations are asynchronous.
Simply move the file-writing code into the callback of the
readFileoperation:Another option would be using
readFileSync()– but that would be a bad idea depending on when you do that (e.g. if the oepration is caused by a HTTP request from a user)