Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

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

According to TutorialsPoint, this is how you create 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 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 mkdir command. Seems like a lot of unnecessary code.

like image 268
Richard Hamilton Avatar asked May 22 '15 15:05

Richard Hamilton


People also ask

What is FS in Nodejs?

js provides an inbuilt module called FS (File System). Node. js gives the functionality of file I/O by providing wrappers around the standard POSIX functions. All file system operations can have synchronous and asynchronous forms depending upon user requirements.

Which of the following methods in the FS module is used for creating a directory?

Creating Permanent Directories with fs. mkdir Family of Functions. To create permanent directories, we can use the mkdir function to create them asynchronously.

Which method is used to create a directory in node JS?

mkdir() method i Node. js is used to create a directory asynchronously.

Is FS mkdir a promise?

The fsPromises. mkdir() method is used to asynchronously create a directory then resolves the Promise with either no arguments, or the first directory path created if recursive is true.


2 Answers

As of node v10.0, the callback to fs.mkdir() is required. You must pass it, even if you just pass a dummy function that does nothing.

The point of the callback is to let you know if and when the call succeeded and if it didn't succeed, what the specific error was.

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.

In response to one of your other comments, the fs.mkdir() function is always asynchronous whether you pass the 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');
            }
        });
    }
});

Note: Modern versions of nodejs, include fs.promises.mkdir() which returns a promise that resolves/rejects instead of using plain callbacks. This allows you to use await with try/catch or .then() and .catch() instead of the plain callback to know when it's done and promises make it typically easier to sequence in with other asynchronous operations and to centralize error handling.

like image 175
jfriend00 Avatar answered Oct 22 '22 18:10

jfriend00


Because mkdir is 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:

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

You can still use mkdirSync if you need a sync version.

like image 43
Pierrickouw Avatar answered Oct 22 '22 20:10

Pierrickouw