NodeJS Basic FileIO

Just testing NodeJS and still learning to think in javascript, how can I get this basic FileIO operation to work?

Here is what I would like to do:

  • Reading an XML file (reading into memory)
  • Put all contents in a variable
  • Writing an XML file from a variable
  • The output must match the source 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);
    }
});
+5
source share
1 answer

The problem with your code is that you are trying to write the data that you are reading to the target file before it is read - these operations are asynchronous.

Just move the file write code to the operation callback readFile:

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);
        }
    });
});

readFileSync() - , (, HTTP- )

var data = fs.readFileSync(filepath, 'utf-8');
fs.writeFileSync('c:/testout.xml', data);
+11

All Articles