首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >这是NodeJS的正确行为吗?

这是NodeJS的正确行为吗?
EN

Stack Overflow用户
提问于 2014-02-19 07:23:44
回答 1查看 56关注 0票数 1

我使用fs.readdir获得了一个文件列表,并将前5个文件尝试读取其内容。

代码语言:javascript
复制
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新手,这是异步特性的一部分吗?还是我做错了什么?

代码语言:javascript
复制
28965131362770944.txt
28965131668946944.txt
28965131803168769.txt
28965131991912448.txt
28965132189040641.txt 
代码语言:javascript
复制
    <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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-19 07:30:16

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

如果要打印“文件名-内容”、“文件名-内容”等序列,则需要为readContent()方法提供文件名,然后将其记录在readFile()方法中。就像这样。

代码语言:javascript
复制
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);
    });
}

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21873705

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档