javascript 使用 NodeJS FS mkdir 时,包含回调的重要性是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30400603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:08:21  来源:igfitidea点击:

When working with NodeJS FS mkdir, what is the importance of including callbacks?

javascriptnode.jscallbackfilesystems

提问by Richard Hamilton

I'm playing with the NodeJS REPLconsole and following this tutorial.

我正在使用NodeJS REPL控制台并按照本教程进行操作。

http://www.tutorialspoint.com/nodejs/nodejs_file_system.htm

http://www.tutorialspoint.com/nodejs/nodejs_file_system.htm

I'm focusing on the File System(FS)module. Let's look at the mkdirfunction used for creating directories.

我专注于File System(FS)模块。让我们看看mkdir用于创建目录的函数。

According to TutorialsPoint, this is how you create a directory with FS

根据 TutorialsPoint,这就是您使用 FS 创建目录的方式

var fs = require("fs");

console.log("Going to create directory /tmp/test");
fs.mkdir('/tmp/test',function(err){
   if (err) {
       return console.error(err);
   }
   console.log("Directory created successfully!");
});

They specifically say you need this syntax

他们特别说你需要这个语法

fs.mkdir(path[, mode], callback)

Well I just tried using less code without the callback and it worked.

好吧,我只是尝试在没有回调的情况下使用更少的代码并且它起作用了。

var fs = require('fs');
fs.mkdir('new-directory');

And the directory was created. The syntax should just be

并创建了目录。语法应该只是

fs.mkdir(path);

I have to ask, what is the purpose of the callback and do you really need it? For removing a directory I could understand why you would need it, in case the directory didn't exist. But I can't see what could possibly go wrong with the mkdircommand. Seems like a lot of unnecessary code.

我不得不问,回调的目的是什么,你真的需要它吗?为了删除目录,我可以理解您为什么需要它,以防目录不存在。但我看不出该mkdir命令可能出现什么问题。好像有很多不必要的代码。

回答by jfriend00

The callback is required when you need to know if/when the call succeeded. If you don't care when it's done or don't care to see if there is an error, then you don't have to pass the callback.

当您需要知道调用是否/何时成功时需要回调。如果您不在乎何时完成或不在乎是否有错误,那么您不必传递回调。

Remember, this type of function is asynchronous. It completes some unknown time in the future so the only way to know when it is done or if it completed successfully is by passing a callback function and when the callback is called, you can check the error and see that it has completed.

请记住,这种类型的函数是异步的。它在未来的某个未知时间完成,因此知道何时完成或是否成功完成的唯一方法是传递回调函数,当回调被调用时,您可以检查错误并查看它是否已完成。

As it turns out, there are certainly things that can go wrong with mkdir()such as a bad path, a permissions error, etc... so errors can certainly happen. And, if you want to immediately use that new directory, you have to wait until the callback is called before using it.

事实证明,肯定会出现一些问题,mkdir()例如错误的路径、权限错误等……所以错误肯定会发生。而且,如果您想立即使用该新目录,则必须等到回调被调用后再使用它。

In response to one of your other comments, the fs.mkdir()function is always asynchronous whether you pass the callback or not.

为了响应您的其他评论之一,fs.mkdir()无论您是否传递回调,该函数始终是异步的。

Here's an example:

下面是一个例子:

var path = '/tmp/test';
fs.mkdir(path, function (err) {
    if (err) {
        console.log('failed to create directory', err);
    } else {
        fs.writeFile(path + "/mytemp", myData, function(err) {
            if (err) {
                console.log('error writing file', err);
            } else {
                console.log('writing file succeeded');
            }
        });
    }
});

回答by Pierrickouw

Because mkdiris async.

因为mkdirasync.

Example:

例子:

If you do:

如果你这样做:

fs.mkdir('test');
fs.statSync('test').isDirectory();//might return false cause it might not be created yet

But if you do:

但如果你这样做:

fs.mkdir('test', function() {
    fs.statSync('test').isDirectory();//will be created at this point
});

You can still use mkdirSyncif you need a syncversion.

如果您需要一个版本,您仍然可以使用mkdirSyncsync

回答by Nicholas Valbusa

Many things could go wrong by using mkdir, and you should probably handle exceptions and errors and return them back to the user, when possible.

使用 可能会出现很多问题mkdir,您可能应该处理异常和错误,并在可能的情况下将它们返回给用户。

e.g. mkdir /foo/barcould go wrong, as you might need root(sudo) permissions in order to create a top-level folder.

例如mkdir /foo/bar可能会出错,因为您可能需要root(sudo) 权限才能创建顶级文件夹。

However, the general idea behind callbacks is that the method you're using is asynchronous, and given the way Javascript works you might want to be notified and continue your program execution once the directory has been created.

但是,回调背后的一般思想是您使用的方法是异步的,并且考虑到 Javascript 的工作方式,您可能希望在创建目录后收到通知并继续执行程序。

Update: bare in mind that if you need — let's say — to save a file in the directory, you'll need to use that callback:

更新:请记住,如果您需要——比方说——将文件保存在目录中,您将需要使用该回调:

fs.mkdir('/tmp/test', function (err) {
    if (err) {
        return console.log('failed to write directory', err);
    }

    // now, write a file in the directory
});

// at this point, the directory has not been created yet

I also recommend you having a look at promises, which are now being used more often than callbacks.

我还建议您查看 Promise,它现在比回调使用得更频繁。

回答by marekful

Because it's an async call, it may be that further execution of the program depends on the outcome of the operation (dir created sucessfully). When the callback executes is the first point in time when this can be checked.

因为它是一个异步调用,所以程序的进一步执行可能取决于操作的结果(目录创建成功)。回调执行时是第一个可以检查的时间点。

However, this operation is really fast, it may seem as it's happening instantly, but really (because it's async), the following line after fs.mkdir(path);will be executed without waiting for any feedback from the fs.mkdir(path);thus w/o any guarantee that the directory creation finished already, or if it failed.

然而,这个操作真的很快,它可能看起来是立即发生的,但实际上(因为它是异步的),下面的行将在fs.mkdir(path);不等待任何反馈的情况下执行,fs.mkdir(path);因此没有任何保证目录创建已经完成,或者如果失败。