0

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Daniel Doinov
  • 289
  • 3
  • 4

2 Answers2

0

Finaly figured it out.

The problem was that I didnt notice that fs.readFileSync had no callback funtction.

So the proper use for that function should have been

var result= fs.readFileSync(pathToFile,{options})
return result;

I can still use some help on the problem i mentiond with next(connection);. I dont realy know why it skips whole parts of code like that.

Daniel Doinov
  • 289
  • 3
  • 4
0

I've found next() doesn't like it if you pass it any parameters. I had a bug in my application for a good day or two because I was doing '.then(next);'

Prometheus
  • 61
  • 7