简体   繁体   English

node.js如何使用单个进程实现异步回调

[英]How node.js implement async-callback with single process

I don't know how node implement its amazing idea. 我不知道节点如何实现其惊人的想法。 And i have a question when use it. 我在使用它时有一个问题。
I have to read four files file1.js file2.js file3.js file4.js and concat them into one big javascript file result.js . 我必须读取四个文件file1.js file2.js file3.js file4.js并将它们连接成一个大的javascript文件result.js It's important to keep their order. 保持秩序很重要。

So it's normal for me to use readFileSync instead of readFile . 所以我使用readFileSync而不是readFile是正常的。
I know it's a bad solution. 我知道这是一个糟糕的解决方案。 Anyone has a good idea to do that? 有人有个好主意吗?

Q: Is it possible for node.js to read four files at the same time? 问: node.js是否可以同时读取四个文件?

Hope someone can explain the principle of node.js and when process.nextTick will be fired. 希望有人能解释node.js的原理以及何时触发process.nextTick。

A: yes it is possible for node to read 4 files at the same time. 答:是的,节点可以同时读取4个文件。

My answer would be, it depends on your situation, for reading the files synchronously or asynchronously. 我的答案是,这取决于你的情况,同步或异步读取文件。 If it's configuration data, or the files can be cached, I would suggest just doing it synchronously, it's easy, and it's only done once. 如果它是配置数据,或者文件可以缓存,我建议只是同步执行,这很容易,而且只执行一次。 So you won't be waiting around very much. 所以你不会在等待。 Long operations on initialization are typical, and can make things in the long run more efficient. 初始化的长时间操作是典型的,并且可以使长期运行更有效。 That being said, reading four files in order, asynchronously, so that your program can do other things in the background isn't that hard. 话虽这么说,异步读取四个文件顺序,以便你的程序可以在后台做其他事情并不难。 I will work on sync and async examples of each and add an edit. 我将处理每个的同步和异步示例并添加编辑。

/* jshint node:true*/

var fs = require('fs');

function readFilesSync(fileNames) {
    'use strict';
    var results = '';

    for (var i = 0; i < fileNames.length; i++) {
        results += fs.readFileSync(fileNames[i]);
    }

    return results;
}

function readFiles(fileNames, callback) {
    'use strict';
    var results = '';

    function readFile(index) {
        if (index < fileNames.length) {
            fs.readFile(fileNames[index], function (err, data) {
                results += data;
                readFile(index + 1);
            });
        } else {
            callback(results);
        }
    }

    readFile(0);
}

function readAllFilesAtOnce(fileNames, callback) {
    'use strict';
    var results = {};
    var numFiles = fileNames.length;

    function callBackWrapper() {
        var resultsOrdered = '';

        for (var i = 0; i < fileNames.length; i++) {
            resultsOrdered += results[fileNames[i]];
        }
        callback(resultsOrdered);
    }

    function readFileAsync(fileName) {
        fs.readFile(fileName, function (err, data) {
            results[fileName] = data;
            numFiles--;

            if (numFiles === 0) {
                callBackWrapper();
            }
        });
    }

    for (var i = 0; i < fileNames.length; i++) {
        readFileAsync(fileNames[i]);
    }

}

function doSomethingWithTheData(data) {
    'use strict';
    console.log('Results async: ' + data);
}

function doSomethingWithTheData2(data) {
    'use strict';
    console.log('Results async all at once: ' + data);
}

var fileNamesArray = ['blah.js', 'file.js', 'hello.txt'];

console.log('The results sync: ' + readFilesSync(fileNamesArray));

readFiles(fileNamesArray, doSomethingWithTheData);

readAllFilesAtOnce(fileNamesArray, doSomethingWithTheData2);

EDIT: There I added a method to read all of the files at once. 编辑:在那里我添加了一个方法来一次读取所有文件。

Process.nextTick does no more than process this function on the next time around the event loop. Process.nextTick只会在下一次围绕事件循环处理此函数。 EX: EX:

process.nextTick(function() {
    console.log('never printed out');
});

while(true);

ex 2: 前2:

process.nextTick(function() {
        console.log('printed last');
});

console.log('printed first');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM