Synchronous & Blocking Javascript Tutorial

12/16/2022
Table of contents

This is required reading for the Code Chrysalis Immersive Bootcamp’s precourse — a series of assignments, projects, assessments, and work that all students must successfully complete remotely before embarking on our full-stack software engineering course.

Before You Begin

  • You will need to have Node installed on your computer. A simple way of describing Node is that it is a program that will allow you to run JavaScript on your computer (rather than just in the browser). This means that you will be able to control, among other things, your file system! If you are new to Node, please check out Node School to get started.
  • This is a hands-on tutorial, so you will need to follow along and play around with the code yourself.
  • Learning to look through and read documentation is a very important skill for software engineers. Please practice looking through the NodeJS documentation as you are going through this tutorial. Please be cognizant of the version of Node that you have and the documentation version that you are looking at.

Synchronous & Blocking

Let's create a function:


console.log('1'); function hello() { console.log('hello'); } console.log('2'); hello(); console.log('3');

Can you predict the output?

Answer:

1 2 hello 3


What if hello was instead a long-running operation, though? Like a database lookup or HTTP request? Don't worry about how it's implemented, just supposed that if it were, then hello would take a lot longer to complete.

Does this mean that we can't call the last console.log until it's complete? With JavaScript, yes. That's because JavaScript can only do one thing at a time (advanced: single-threaded). This would be, what we call, a synchronous operation.

With a synchronous operation, if something takes a long time, then that function would block the rest of the code from running until the operation is completed.

On a browser, that can mean an unresponsive web page.

On a server, that can mean requests would stop being processed.

Switching gears a little bit…

Introducing fs

Unlike the browser, where everything is global, in Node there are only two global things: a module object, and a require() function.

We'll get into module later, for now, let's require() fs:

const fs = require('fs'); console.log(fs);


What is fs? There are two ways to find out:

  • Check the docs
  • console.log() it!

We see a lot of file related methods, so one could deduce that it stands for "file system".

In your current directory, run the following command:

echo 'hello world' >> index.js


Then run the following in Node:

const fs = require('fs'); const result = fs.readFileSync('index.js', 'utf8'); console.log(result);


What is the result? What happens if you don't include 'utf8'? What is 'utf8'?

Blocking Behavior

In our above example, take note that the console.log does not run until we are done reading the file. Try modifying index.js so that it is a huge chunk of code. Does that change the order?

No.

This is because fs.readFileSync is exacty as its name suggests---it is a synchronous method and therefore, blocking. No matter how large the file, our JavaScript will wait until fs.readFileSync is completely done with reading it.

Let's check this out with regular JavaScript.

Blocking Behavior with Higher Order Functions

Let's create a higher order function now and provide hello to it as a callback.

console.log('1'); function hello() { console.log('hello'); }; console.log('2'); function invokeNow(action) { console.log('3'); action(); } console.log('4'); invokeNow(hello) console.log('5');


Can you predict the output?

Answer:

1 2 4 3 hello 5


invokeNow(hello) is still exhibiting blocking behavior. We have to wait until all of that is done before we print 5.

Challenges

  1. Can you use fs.readFileSync() to read non-JavaScript files? Like a JSON file or a text (.txt) file? How about an html file? Try it.
  2. What are other options besides 'utf8'?
  3. The opposite of synchronous is called asynchronous. What do you think asynchronous means?
  4. Explore fs.readFile. This is the asynchronous version of fs.readFileSync. How do you use it? What does it do differently?

Resources

Here are a couple of resources. These are not the only resources out in the internet, so please look around and find other resources to supplement as needed.

Code Chrysalis is a Tokyo-based 🗼 coding school providing a full-time and part-time programming courses in English and Japanese. Join us in-person or take our classes remotely. See why we are an industry leader in technical education in Japan 🗾.

We also put on free workshops and events for the community, so follow us for the latest!

👋 Follow us on…

YouTube - Instagram - Facebook - Twitter - 日本語版 Twitter - LinkedIn

This is the beginning of an introduction into the blocking nature of JavaScript. In the process, you’ll also be doing more exploring of various Node modules, like fs.

 ブログ

全部
Interview header image

【企業向け研修】オープンコースインタビュー PCA株式会社:受講者様

今回は、企業向け研修プログラムの他企業合同で​受講可能な​『オープンコース』を導入していただいたPCA株式会社の方に、本コースを受講した前後の変化などについてお聞きしました。 オープンコースとは、 目覚ましくIT技術が進化していく時代で、既存のエンジニアの社員をチームや企業の目標に合わせた最新のエンジニアリングスキルセットをそなえた人材に育てるプログラミング研修です。また、従来の​アップスキリングコースの​課題でも​あった​人数制限や​費用の​改善を​加え、​より​多くの​方​々に​機会を​ご提供できる​プログラムになっております。

Interview header image

【企業向け研修】オープンコースインタビュー大手金融機関:受講者様

今回は、企業向け研修プログラムの他企業合同で​受講可能な​『オープンコース』を導入していただいた大手金融機関の方に、本コースを受講した前後の変化などについてお聞きしました。 オープンコースとは、 目覚ましくIT技術が進化していく時代で、既存のエンジニアの社員をチームや企業の目標に合わせた最新のエンジニアリングスキルセットをそなえた人材に育てるプログラミング研修です。また、従来の​アップスキリングコースの​課題でも​あった​人数制限や​費用の​改善を​加え、​より​多くの​方​々に​機会を​ご提供できる​プログラムになっております。

Interview header image

他企業合同で受講可能なアップスキリングプログラム『MIXED COURSE』の提供を開始

各企業少人数からの参加を可能にし、個社文化からの逸脱や他社エンジニアとの交流で一人ひとりの向上心を刺激