6.2 Hello world program v2
We'll continue to use Typescript for our examples. The program is the same, with a some additions:
- There are two imports with one import has another inside it
- There is a synchronous op
- There is an asynchronous op
The file name is
helloLogV2.ts.
The location of the source file is:
/Users/mayankc/Work/source/deno-vs-nodejs/helloLogV2.ts
Here is the code that we'll use to understand some new concepts:
import { doze } from 'https://deno.land/x/doze/mod.ts';
import { getMachineId } from 'https://deno.land/x/machine_id/mod.ts';
function printNumber(input: number) {
console.log(input);
}
function printString(input: string) {
console.log(input);
}
await getMachineId();
await doze(1);
printNumber(1);
printString('One');
console.log(Deno.env.get('TEST_ENV'));
await Deno.truncate('/var/tmp/test.log');
This is still a simple program with just one typescript file. At the start of the program, there is are two imports to get ES modules: doze and machine_id. Doze is chosen over delay because doze has no further dependencies, while delay comes with a lot of std modules. Using doze makes it simpler and manageable. The second module is machine_id which also has zero dependencies. None of these imported modules would get used in the code. These modules are there only to show how imports work.
The first part of the program is different. There are calls to use the imported modules. This part is there to show how imports work. We won't go over the awaits on lines 12, 13 in this book.
Next, print number 1 and word One on the console. The next line gets an environment variable TEST_ENV and prints it on the console. The reason to choose this is to show how sync ops are implemented by Deno. The next line calls the truncate function which truncates a file. The reason to choose this is to show async ops are implemented by Deno. Then the program finishes.
Simple enough. But very useful in learning new concepts like imports, sync, and async ops.
As mentioned before, we'll not go over all the concepts again as that'd be a repetition. Instead, we'll focus only on new concepts like:
- Imports
- Sync ops
- Async ops
After conversion to JS, the program looks like this:
import { doze } from 'https://deno.land/x/doze/mod.ts';
import { getMachineId } from 'https://deno.land/x/machine_id/mod.ts';
function printNumber(input) {
console.log(input);
}
function printString(input) {
console.log(input);
}
await getMachineId();
await doze(1);
printNumber(1);
printString('One');
console.log(Deno.env.get('TEST_ENV'));
Deno.truncate('/var/tmp/test.log');
This is almost the same as before, except for import and ops.
--
Just to recall, the main worker works in two phases: load module and evaluate the module. The loading part would be different because there are imports.
Let's jump directly to something new, which is building the module graph for a program that has some imports.