Let's have a look at asynchronous programming model that is at the heart of how Node.js works.
Callbacks are functions that are executed asynchronously, or at a later time. Instead of the code reading top to bottom procedurally, asynchronous programs may execute different functions at different times based on the order and speed of earlier functions.
Since JavaScript treats functions like any other object, we can pass a function as an argument in another function and alter execute that passed-in function or even return it to be executed later.
We saw such a function previously when we were looking at the fs
module in The Module System section. Let's revisit it:
const fs = require('fs'); let file = `${__dirname}/temp/sample.txt`; fs.readFile(file, 'utf8', (err, data) => { if (err) throw err; console.log(data); });
Note
The code files for Asynchronous Programming with Node.js are placed at Code/Lesson-1/c-async-programming
.
On line 3, we use a variable part of the globals
, _ _dirname
, which basically gives us the absolute path of the directory (folder) in which our current file (read-file.js
) is, from which we can access the temp/sample.txt
file.
Our main point of discussion is the chunk of code between lines 5 and 8. Just like most of the methods you will come across in Node.js, they mostly take in a callback function as the last argument.
Most callback functions will take in two parameters, the first being the error object and the second, the results. For the preceding case, if file reading is successful, the error object, err
, will be null and the contents of the file will be returned in the data object.
Let's break down this code for it to make more sense:
const fs = require('fs'); let file = `${__dirname}/temp/sample.txt`; const callback = (err, data) => { if (err) throw err; console.log(data); }; fs.readFile(file, 'utf8', callback);
Now, let's look at the asynchronous part. Let's add an extra line to the preceding code:
const fs = require('fs'); let file = `${__dirname}/temp/sample.txt`; const callback = (err, data) => { if (err) throw err; console.log(data); }; fs.readFile(file, 'utf8', callback); console.log('Print out last!');
See what we get as a print out:
Print out last! hello, world
How come Print out last!
comes first? This is the whole essence of asynchronous programming. Node.js still runs on a single thread, line 10 executes in a non-blocking manner and moves on to the next line, which is console.log('Print out last!')
. Since the previous line takes a long time, the next one will print first. Once the readFile
process is done, it then prints out the content of file through the callback.
Promises are an alternative to callbacks for delivering the results of an asynchronous computation. First, let's look at the basic structure of promises, before we briefly look at the advantages of using promises over normal callbacks.
Let's rewrite the code above with promises:
const fs = require('fs'); const readFile = (file) => { return new Promise((resolve, reject) => { fs.readFile(file, 'utf8', (err, data) => { if (err) reject(err); else resolve(data); }); }); } // call the async function readFile(`${__dirname}/../temp/sample.txt`) .then(data => console.log(data)) .catch(error => console.log('err: ', error.message));
This code can further be simplified by using the util.promisify
function, which takes a function following the common Node.js callback style, that is, taking an (err, value) => …
callback as the last argument and returning a version that returns promises:
const fs = require('fs'); const util = require('util'); const readFile = util.promisify(fs.readFile); readFile(`${__dirname}/../temp/sample.txt`, 'utf8') .then(data => console.log(data)) .catch(error => console.log('err: ', error));
From what we have seen so far, promises provide a standard way of handling asynchronous code, making it a little more readable.
What if you had 10 files, and you wanted to read all of them? Promise.all
comes to the rescue. Promise.all
is a handy function that enables you to run asynchronous functions in parallel. Its input is an array of promises; its output is a single promise that is fulfilled with an array of the results:
const fs = require('fs'); const util = require('util'); const readFile = util.promisify(fs.readFile); const files = [ 'temp/sample.txt', 'temp/sample1.txt', 'temp/sample2.txt', ]; // map the files to the readFile function, creating an // array of promises const promises = files.map(file => readFile(`${__dirname}/../${file}`, 'utf8')); Promise.all(promises) .then(data => { data.forEach(text => console.log(text)); }) .catch(error => console.log('err: ', error));
This is one of the latest additions to Node.js, having been added early in 2017 with version 7.6, providing an even better way of writing asynchronous code, making it look and behave a little more like synchronous code.
Going back to our file reading example, say you wanted to get the contents of two files and concatenate them in order. This is how you can achieve that with async
/await
:
const fs = require('fs'); const util = require('util'); const readFile = util.promisify(fs.readFile); async function readFiles() { const content1 = await readFile(`${__dirname}/../temp/sample1.txt`); const content2 = await readFile(`${__dirname}/../temp/sample2.txt`); return content1 + '\n - and - \n\n' + content2; } readFiles().then(result => console.log(result));
In summary, any asynchronous function that returns a promise can be awaited.
Before You Begin
You should have already gone through the previous activities.
Aim
Read the file (using fs.readFile
), in-file.txt
, properly case format the names (using the lodash
function, startCase
), then sort the names in alphabetical order and write them out to a separate file out-file.txt
(using fs.writeFile
).
Scenario
We have a file, in-file.txt
, containing a list of peoples' names. Some of the names have not been properly case formatted, for example, john doe
should be changed to John Doe
.
Steps for Completion
In
Lesson-1
, create another folder calledactivity-c
.- On the Terminal, change directory to
activity-c
and run the following command:
npm init
- Just like in the previous activity, this will take you to an interactive prompt; just press Enter all the way, leaving the answers as suggested defaults. The aim here is for us to get a
package.json
file, which will help us organize our installed packages. - Since we will be using
lodash
here too, let's install it. Run,npm install lodash --save
. - Copy the
in-file.txt
file provided in thestudent-files
directory into youractivity-c
directory. - In your
activity-c
directory, create a file calledindex.js
, where you will write your code. - Now, go ahead and implement an
async
functiontransformFile
, which will take the path to a file as an argument, transform it as described previously (under Aim), and write the output to an output file provided as a second parameter. - On the Terminal, you should indicate when you are reading, writing, and done, for example:
reading file: in-file.txt
writing file: out-file.txt
done
Note
You should read the quick reference documentation on fs.writeFile
since we haven't used it yet. However, you should be able to see its similarity with fs.readFile
, and convert it into a promise function, as we did previously.
The solution files are placed at Code/Lesson-1/activitysolutions/activity-c
.