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:
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 readFile
operation:
fs.readFile(filepath, 'utf8', function(err, data) {
if(err) {
console.error("Could not open file: %s", err);
return;
}
fs.writeFile('c:/testout.xml', data, function(err) {
if(err) {
console.error("Could not write file: %s", err);
}
});
});
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)
var data = fs.readFileSync(filepath, 'utf-8');
fs.writeFileSync('c:/testout.xml', data);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With