Infinite | Squares

Art of code and more

Friendly Node.js Error Message

While working with Node.js, I used fs module often. One function that I used frequently is fs.exists() to check if the file is there before doing any processing. Today, I read through Node.js fs documentation and found the following :

fs.exists() is an anachronism and exists only for historical reasons. There should almost never be a reason to use it in your own code.

In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to fs.exists() and fs.open(). Just open the file and handle the error when it’s not there.

It make sense. Suppose we want to get file stat using fs.stat(), just call the function and see the error code. If the file is not exists, then you will have this error :

1
2
3
4
{ [Error: ENOENT, stat 'c:\Users\ArifSetiawan\Repository\CymbRef\cmd\somefile']
  errno: 34,
  code: 'ENOENT',
  path: 'c:\\Users\\ArifSetiawan\\Repository\\CymbRef\\cmd\\somefile' }

Node.js use POSIX codes to denote errors and its a long list. How do you translate the error ENOENT into friendly error message. Do you even know that ENOENT means No such file or directory?

Lucky for us, Rod Vagg (rvagg) has created a node modules which give description for all kinds of errno in Node.js named errno. Using example from the readme :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var fs = require('fs');
var errno = require('errno');

function errmsg(err) {
    var str = 'Error: '
    // if it's a libuv error then get the description from errno
    if (errno.errno[err.errno]) {
        str += errno.errno[err.errno].description
    } else {
        str += err.message
    }

    // if it's a `fs` error then it'll have a 'path' property
    if (err.path) {
        str += ' [' + err.path + ']'
    }
    return str
}

fs.stat('filenotexists', function(err, stats) {
  console.error(errmsg(err));
})

We can have human friendly readable error

1
Error: no such file or directory [c:\Users\ArifSetiawan\Repository\CymbRef\cmd\filenotexists]

Comments