【问题标题】:Synchrone issue readdir with singleton in Node.js在 Node.js 中将问题 readdir 与单例同步
【发布时间】:2014-01-26 04:59:32
【问题描述】:

第一个使用 Node.js 的应用程序,尝试在单例类中探索文件以从中获取内容,但顺序不是我所期望的。我肯定缺少一个知识,你能告诉我为什么..

单例类:

var Singleton = (function()
{
    var _instance = null;

    return new function()
    {
        this.Instance = function()
        {
            if (_instance == null)
            {
                _instance = new Foo();
            }
            return _instance;
        }
    };
})();

Foo 类:

var Foo= function Foo()
{
    this._filesDir= "./core/files/";
    this._storedFiles = {};

    this.method1();
console.log("call constructor");
};

Foo.prototype = {
    method1: function()
    {
        console.log("call method1");
        var that = this;

        var c = 0;

        fs.readdirSync(this._filesDir).forEach(function(fileName)
        {
            console.log("iterating file"+ c);

            c++;
            fs.readFile(that._filesDir + fileName, 'utf-8', function(err, content)
            { 
                var clean_FileName = fileName.replace(".txt", "");
                console.log( clean_fileName );
                that._storedFiles[ clean_fileName ] = content;
            });
        });
    },

    method2: function( fileName )
    {
        console.log('call method2');
        return ( fileName in this._storedFiles);
    }
};

呼唤:

console.log( Singleton.Instance().method2("myfile") );

目录中只有这个myfile.txt

但是,控制台向我显示:

call method1
iterating file0
call constructor
call method2
false
GET /test 304 11ms
myfile

所以我的回答是错误的,这个普通的构造函数是在第三个位置调用的吗?我需要类构造、存储并最终执行method2()。我做错了什么?

【问题讨论】:

    标签: javascript node.js singleton


    【解决方案1】:

    问题的根源在于 fs.readFile 是异步的。 method1 在您读取文件内容之前返回。一个简单的解决方法是将其更改为 fs.readFileSync

    “调用构造函数”之所以是第三个,是因为你先调用了method1()。

    this.method1();
    console.log("call constructor");
    

    method1 中的所有内容都在 console.log("call constructor") 发生之前运行。如果您希望顺序正确,您可以简单地交换两者。

    从高层次来看,使用同步调用(readdirSync、readFileSync)通常是个坏主意,因为它们会阻止 Node 在运行时执行任何其他操作。我建议研究 Node.js 的回调、控制流和异步特性。那里有很多很棒的教程。

    【讨论】:

    • 就是这样。关于概念问题,我整理了this.method1();从构造函数,并简单地在应用程序的主要开始调用它,而我最终将 readdirSync 编辑为 readdir。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    • 2015-02-23
    • 2016-07-18
    • 2022-01-22
    • 1970-01-01
    • 2018-01-19
    相关资源
    最近更新 更多