I have a node.js script that reads in some JS code from a file, and passes it to an eval(). The code that passes the javascript to the eval is as follows:
// read javascript code from file
var outputbuffer = '';
function output(data) {
outputbuffer += data + '\n';
}
eval(javascriptCodeFromFile);
// do stuff with outputbuffer
The javascript code in the file is as follows:
var fs = require('fs');
fs.readFile('myfile.txt', function(err, data) {
if (err) {
output('Error reading file');
}
else {
output(data.toString());
}
});
The problem is that the eval exits before the file read completes, as the file read is asyncronous. The eval simply starts the file read, and then exits, not waiting from the file read to complete. How can I make the eval wait for the callback before exiting? I have looked at promises and they seem PROMISing (pun intended) but I need someone to guide me in the right direction.