I'm obviously missing something very important about how Node.js and Actionhero work.
Can someone please explain to me why the following problem occurs:
I have this simple code: Basically it reads a .css file .
buildAdsHTML: function (ads, type) {
var cssDir = path.normalize(__dirname + '/../public/css/');
switch (type) {
case 'text':
var result = '';
console.log("STEP 1");
fs.readFile(cssDir + type + 'Ads.css', {encoding: 'utf8'}, function (err, data) {
console.log(err);
console.log(data);
if (!err) {
console.log("STEP 2");
result += '<style>' + data + '</style>';
} else {
}
});
break;
}
console.log('STEP 3');
return result;
}
Now when this code is run I get an empty string as result. The console output is the following:
STEP 1 <- so far so good
STEP 3<- this should be last!
null <- this is the error variable
.some-random-css-class{
display: block;
width: 100;
min-height: 250px;
}
STEP 2
Now at some point I figured out that that fs.reafFile
is async function.
So I naturaly changed it to the sync version fs.readFileSync
.
Now the console output is even worse:
STEP 1
STEP 3
Thats it! Nothing else.
And I still get a empty string as result.
Like the whole code isnt even going through the swich
.
I've noticed this behavior in all functions and methods of my actionhero project,
most notebly when calling next(connection)
. You can't just call it at the end of the method.
For every if
or swich
I have to call it inside to have any actual control over the result.
Otherwise every new data I've added to the connection is lost.
What's with that ? Please explain that functionality in detail so I don't make any dumn mistakes while coding.