JavaScript for Absolute Beginners 4

In this tutorial, we’re going to write a JavaScript program to do temperature conversion (i.e. Celsius to Fahrenheit and vice versa).



Other tutorials of this series.

Notes for this tutorial:

Task for this tutorial:

  • Given a CSV file containing the weather data
  • Convert each of the weather data into Celsius or Fahrenheit depending on the original unit
  • Write the converted weather data into the output file in the same CSV format.

Concepts about software development:

  • Understanding the concepts is much more important than knowing the syntax of programming languages
  • In order to solve a big problem, always break it into smaller subproblems

Using modules (ES5 CommonJS syntax)

Import modules
1
2
const fs = require("fs");
const readline = require("readline");

Program arguments

Program arguments
1
2
3
4
//process.argv is an array
//$ node programName arg1 arg2
const arg1 = process.argv[2];
const arg2 = process.argv[3];

Read text file line by line

Read text file line by line
1
2
3
4
5
6
7
8
9
const fileReadStream = fs.createReadStream("filename.txt");

const rl = readline.createInterface({
input: fileReadStream
});

rl.on('line', (line) => {
//do something
});

Write text file

Write text file
1
2
const fileWriteStream = fs.createWriteStream("outputFilename.txt");
fileWriteStream.write(`hello world`);

Blocking (synchronous) calls VS non-blocking (asynchronous) calls

  • Blocking: need to wait for the call to complete before you can proceed to the next line
  • Non-blocking: you don’t have to wait for the call to complete. You can still execute the subsequent instructions

Switch case

Switch case
1
2
3
4
5
6
7
8
9
10
11
12
const someCondition = 'f';
switch (someCondition) {
case 'c':
//do something
break;
case 'f':
//do something
break;
default:
//else
break;
}

The shorthand for if-else statement

The shorthand for if-else statement
1
2
3
4
5
6
7
8
let outputScale = scale === 'c' ? 'F' : 'C';

//same as
if (scale === 'c') {
outputScale = 'F';
} else {
outputScale = 'C';
}

The source code of the program in this tutorial on GitHub.