drhanlau
drhanlau

Reputation: 2527

Is this the right behaviour of NodeJS?

I obtained a list of files using fs.readdir, and take the first 5 files trying to read their content.

files.slice(0,5).forEach(function(item){
                        console.log(item);
                        readContent(path+"/"+item);
                    }
                );


function readContent(filename)
{
    var fs= require("fs");
    fs.readFile(filename, 'utf8', function(err, data)
    {
       console.log(data);
    });
}

But it prints the filename first, then only print the content, instead of "filename -> content" as I expected. I am new to NodeJS, is this part of the asynchronous feature ? Or I did something wrong?

28965131362770944.txt
28965131668946944.txt
28965131803168769.txt
28965131991912448.txt
28965132189040641.txt 

    <script type="text/javascript"> //<![CDATA[ window.location.replace('/#!/LovelyThang80/status/28965131362770944'); //]]> </script>
    <script type="text/javascript"> //<![CDATA[ (function(g){var c=g.location.href.split("#!");if(c[1]){g.location.replace(g.HBR = (c[0].replace(/\/*$/, "") + "/" + c[1].replace(/^\/*/, "")));}else return true})(window); //]]> </script>
    <script type="text/javascript" charset="utf-8">
      if (!twttr) {
        var twttr = {}
      }

      // Benchmarking load time.
      // twttr.timeTillReadyUnique = '1309338925-32926-11310';
      // twttr.timeTillReadyStart = new Date().getTime();
    </script>

        <script type="text/javascript"> //<![CDATA[ var page={};var onCondition=function(D,C,A,B){D=D;A=A?Math.min(A,5):5;B=B||100;if(D()){C()}else{if(A>1){setTimeout(function(){onCondition(D,C,A-1,B)},B)}}}; //]]> </script>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <meta content="en-us" http-equiv="Content-Language" /> <meta content="Chef salad is calling my name, I'm so hungry!" name="description" /> <meta content="no" http-equiv="imagetoolbar" /> <meta content="width = 780" name="viewport" /> <meta content="4FTTxY4uvo0RZTMQqIyhh18HsepyJOctQ+XTOu1zsfE=" name="verify-v1" /> <meta content="1" name="page" /> <meta content="NOODP" name="robots" /> <meta content="n" name="session-loggedin" /> <meta content="LovelyThang80" name="page-user-screen_name" />
    <title id="page_title">Twitter / Miss ImpressiveAngel: Chef salad is calling my n ...</title>
    <link href="http://a1.twimg.com/a/1309298903/images/twitter_57.png" rel="apple-touch-icon" /> <link href="/oexchange.xrd" rel="http://oexchange.org/spec/0.8/rel/related-target" type="application/xrd+xml" /> <link href="http://a3.twimg.com/a/1309298903/images/favicon.ico" rel="shortcut icon" type="image/x-icon" />

    <link href="http://a3.twimg.com/a/1309298903/stylesheets/twitter.css?1309198825" media="screen" rel="stylesheet" type="text/css" /> <lin

Upvotes: 1

Views: 69

Answers (1)

sergej shafarenka
sergej shafarenka

Reputation: 20426

Yes, this is expected behavior. All IO operations in Node.js are done asynchronously. This means console.log(item) will be executed immediately, but reading content will happen a tick later, because of it's asynchronous nature. Thus main thread prints all file names first, and then their content.

If you want to print "filename-content", "filename-content" etc sequence, you need to give file name to the readContent() method and then log it inside readFile() method. Like this.

files.slice(0,5).forEach(function(item){
    readContent(path+"/"+item, item);
});

function readContent(filename, item) {
    var fs = require("fs");
    fs.readFile(filename, 'utf8', function(err, data) {
        console.log(item);
        console.log(data);
    });
}

P.S. There is an option to call fs.readFileSync() which reads file synchronously. I would strongly discourage you from using it in productive code, because for the time a file is read it will stop processing of other incoming requests. Synchronous methods are normally used during application initialization, but never at runtime, when application serves requests.

Upvotes: 1

Related Questions