Easy way to create Node.js callbacks

Panu Viljamaa
1 min readJul 28, 2018

--

Much of the Node.js API [1.] is asynchronous. That means that when you call such an API you pass in a “callback function” as argument, which will get called by the system when the function has its result ready, or it has run into a problem. A typical example of Node.js async API is for instance fs.writeFile() [2.].

Here’s how you might call fs.writeFile() passing in a file-path and a callback as argument:

fs.writeFile
( filePath
, newContent
, function cb (maybeError)
{ if (maybeError)
{ throw "writeFile() failed";
}
}
);

Above is very clear, the only problem is if you need to write it many times. But you don’t need to write the callback-function if you can import it from somewhere.

Assuming you have the open-source library ‘cisf.js’ [3.] latest version 4.3.1 installed (‘npm install cisf’) you can do it like this:

let {err} = require("cisf"); 
fs.writeFile( filePath, newContent, err);

Simple . This of course works only with API-functions which don’t return any data, such as fs.writeFile(). For fs.readFile() you still need a “hand-made” callback because in that case you need to tell what to do with the file-content when the system sends it to you, by calling your callback.

More on Cisf.js

To read more about cisf.js see my previous Medium-post: https://medium.com/@panuviljamaa/canary-in-software-factory-fa786d81c396 .

LINKS:

[1.] https://nodejs.org/api/index.html

[2.] https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback

[3.] https://www.npmjs.com/package/cisf

--

--