Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS Basic FileIO

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);
    }
});
like image 721
Level1Coder Avatar asked Jun 10 '12 00:06

Level1Coder


1 Answers

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);
like image 72
ThiefMaster Avatar answered Sep 24 '22 20:09

ThiefMaster