When working with NodeJS FS mkdir, why is it important to include callbacks?

I am playing with the console NodeJS REPL

and following this tutorial.

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

I am focusing on the module File System(FS)

. Let's look at a function mkdir

used to create directories.

According to TutorialsPoint you are creating a directory with 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 that you need this syntax

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

      

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

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

      

And the directory was created. The syntax should be

fs.mkdir(path);

      

I have to ask, what is the purpose of the callback and do you really need it? For deleting a directory, I could understand why you need this if the directory does not exist. But I don't see what could go wrong with the team mkdir

. Seems like a lot of unnecessary code.

+3


source to share


4 answers


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

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

As it turns out, there are certain things that can go wrong with mkdir()

, for example, wrong path, permissions error, etc ... so errors can happen. And if you want to use this new directory immediately, you need to wait until the callback is called before using it.



In response to one of your other comments, the function is fs.mkdir()

always asynchronous whether you pass in a callback or not.

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');
            }
        });
    }
});

      

+6


source


A lot of things can go wrong using mkdir

, and you should probably handle exceptions and errors and return them to the user whenever possible.

eg. mkdir /foo/bar

might go wrong as you might need root

(sudo) permissions to create top level folder.

However, the general idea behind callbacks is that the method you are using is asynchronous, and given how Javascript works, you might want to be notified and continue running your program after the directory has been created.



Update: Don't forget that if you need - let's say - to save a file in a directory, you need to use this 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 that you take a look at promises, which are now more commonly used than callbacks.

+2


source


Since this is an asynchronous call, it is possible that further program execution depends on the result of the operation (generated by dir). When the callback is executed, this is the first moment in time that it can be checked.

However, this operation is very fast, it may seem like it is instantaneous, but in reality (because it is asynchronous), the next line after fs.mkdir(path);

will be executed without waiting for feedback from fs.mkdir(path);

, thus w / o any guarantee that the directory creation is already complete , or if it failed.

+1


source


Because mkdir async

.

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 this:

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

      

You can use mkdirSync if you need a version sync

.

+1


source







All Articles