简体   繁体   English

什么是 Node.js 中的事件驱动非阻塞 IO 模型?

[英]What is a Event Driven non blocking IO model in Node.js?

I don't understand what is the real difference between the codes:我不明白代码之间的真正区别是什么:

 const fs = require('fs'); fs.readFile('/file.md', (err, data) => { if (err) throw err; });

 const fs = require('fs'); const data = fs.readFileSync('/file.md');

Please somebody tell me what is going on here in simplified way.请有人以简化的方式告诉我这里发生了什么。

In few words the difference is that the first snippet is asynchronous.简而言之,区别在于第一个片段是异步的。

The real difference is when the code after the snippets get executed.真正的区别在于代码片段之后的代码何时被执行。

So if you try to execute:因此,如果您尝试执行:

const fs = require('fs');
console.log('preparing...');
fs.readFile('/file.md', (err, data) => {
  if (err) throw err;
  console.log('I am sure that the data is read!');
  console.log(data);
});

console.log('Not sure if the data is here... ');

you'll see (if the file is big enough):你会看到(如果文件足够大):

preparing...
Not sure if the data is here...
I am sure that the data is read!
$data

In the other case (the readFileSync ), the data will be there (unless of errors).在另一种情况下( readFileSync ),数据将在那里(除非出现错误)。

Take look at this example看看这个例子

var express = require('express');
var fs = require('fs');

var app = express.createServer(express.logger());

app.get('/readFile', function(request, response) {
    fs.readFile('data.txt', function(err, data){
        response.send(data);
    });
});


app.get('/readFileSync', function(request, response) {
   let data =  fs.readFileSync('data.txt');
});

response.send(data);

fs.readFile takes a call back which calls response.send. fs.readFile 接受一个调用 response.send 的回调。 If you simply replace that with fs.readFileSync, you need to be aware it does not take a callback so your callback which calls response.send will never get called and therefore the response will never end and it will timeout.如果你只是用 fs.readFileSync 替换它,你需要注意它不接受回调,所以你调用 response.send 的回调永远不会被调用,因此响应永远不会结束,它会超时。

You need to show your readFileSync code if you're not simply replacing readFile with readFileSync.如果您不是简单地用 readFileSync 替换 readFile,则需要显示您的 readFileSync 代码。

Also, just so you're aware, you should never call readFileSync in a node express/webserver since it will tie up the single thread loop while I/O is performed.此外,正如您所知,您永远不应该在节点 express/webserver 中调用 readFileSync,因为它会在执行 I/O 时占用单线程循环。 You want the node loop to process other requests until the I/O completes and your callback handling code can run.您希望节点循环处理其他请求,直到 I/O 完成并且您的回调处理代码可以运行。 Though you can use the promise to handle this.虽然您可以使用承诺来处理这个问题。

And from v10.0.0 The callback parameter is no longer optional for readFile.并且从 v10.0.0 开始,readFile 的回调参数不再是可选的。 Not passing it will throw a TypeError at runtime.不传递它会在运行时抛出 TypeError。

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

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