DEV Community

Martin Nordström
Martin Nordström

Posted on

Callback Functions in NodeJS

a lot of code!

What is Node.js?

NodeJS is a runtime for server side “Javascripting”. You probably already know that we have Javascript in thr client side (browser) that pretty much power everything we see online. And there’re a lot of different client side frameworks that runs on Javascript, like React, Angular, Vue etc. But what NodeJS lets us do is to run it on the server side.
NodeJS is also an asynchronous platform, it doesn’t wait around for things to finish, it’s non-blocking. But how does it do that? Callbacks!
Callback is a function that is called at the completion of any given task. So if I tell Node to go and to something, once that task is completed we can have a callback function to do something else. It basically allows other code to run in the meantime.
So I’d like to show what that does and what it looks like.

The Code

We can start off by brining in the file system package because I want to work with some files on my disk. I’ve pre-written a file named helloWorld.txt in the same directory as my app.js.

const fs = require('fs')

Now we’re going to make an anonymous function:

const fs = require('fs')
let results = (path) => {
  fs.readFile(path, 'utf8', function(err, contents) {
Enter fullscreen mode Exit fullscreen mode

The first thing we do is passing in the path. Then we want to asynchronously read in a file, so we give it a path, an encoding utf8 and finally we pass in a callback function (I didn’t use an arrow function because it will easier if you see the keyword function). That function will execute once the read file is completed.

This is the order once more:

  • readFile() will run.
  • function(err, contents) will run after readFile() is completed.

In our callback function, we are passing in an error, not because we’ll get one, but because we follow the standard callback pattern. We also pass in the contents that will come back from reading the file.

So far we’ve created a very standard anonymous function (we haven’t given it a name) that takes a path and we store it in the let results.

Finally we can call reader just by calling the function with () and passing in a path.

Hit CMD + S or Ctrl + S , bring up your console and then type node app.js (or whatever you named your file). Your output should be what’s inside of your text file.

And your done!

Top comments (1)

thejscode profile image
Jaskirat Grewal

Hi Martin! Great post. But since you have used the tutorial tag, newbies expect some step by step DIY stuff which they can try out. That's my suggestion. Thank you