~/Home ~/Notes ~/Categories

Intro to Node

22 September, 2020  ·   Node

What is Node and why to use it?

Pros

When to not use Node?

REPL

 1node
 2# acts like a console
 3> greet='क्या हाल है?'
 4'क्या हाल है?'
 5> 7+3
 610
 7> !0
 8true
 9> +'7'
107
11> 3*8
1224
13> _+15 # _ adds 15 to previous value
1439
15> _-30 #subtracts 30 from previous value
169
17> .exit or #ctrl + D

Intro to Node Modules

1const fs = require("fs"); //returns an object with lots of fns which we can later use

fs module

reading and writing files

readFileSync():

1const fs = require("fs");
2//reads data from file and encodes in readable format
3const textIn = fs.readFileSync("./txt/input.txt", "utf-8"); // if we dont specify encoding, we get buffer as output
4console.log(textIn);

writeFileSync():

1const textOut = `This is what we know about : ${textIn}.\nCreated on ${Date.now()}`;
2fs.writeFileSync("./txt/output.txt", textOut);
3console.log("File written");

Blocking and Non-blocking async nature of Node

Async version of previous code …

1fs.readFile("./txt/input.txt", "utf-8", (err, data) => {
2  if (err) throw new Error();
3  console.log(data);
4});
5console.log("reading file...");

Reading and Writing files Asynchronously (Non-blocking way)

readFile():

1fs.readFile("./txt/start.txt", "utf-8",
2(err, data) => {
3    console.log(data)
4}
5console.log("will read first")
6//output:
7// will read file
8//text in start.txt
 1fs.readFile("./txt/start.txt", "utf-8", (err, data1) => {
 2  fs.readFile(`./txt/${data1}.txt`, "utf-8", (err, data2) => {
 3    //2nd readFile depends on 1st one coz we are using data of file1 as the name of file2
 4    console.log(data2);
 5    fs.readFile(`./txt/append.txt`, "utf-8", (err, data3) => {
 6        console.log(data3);
 7    }
 8  });
 9});
10console.log("will read file!");
11//output:
12//will read file
13//output of data2
14//output of data 3

writeFile() :

 1fs.readFile("./txt/start.txt", "utf-8", (err, data1) => {
 2    if(err) return console.log(`ERROR!! ${err} 😥`);
 3  fs.readFile(`./txt/${data1}.txt`, "utf-8", (err, data2) => {
 4      if(err) return console.log(`ERROR!! ${err} 😥`);
 5    console.log(data2);
 6    fs.readFile(`./txt/append.txt`, "utf-8", (err, data3) => {
 7        if(err) return console.log(`ERROR!! ${err} 😥`);
 8        console.log(data3);
 9        fs.writeFile(`./txt/final.txt`, `${data2}\n${data3}`, "utf-8",
10        (err) => { //no data to read, so only one arg: err
11            console.log('file has been written 😁')
12        })
13    }
14  });
15});
16console.log("will read file!");
17//output:
18// will read file
19//output of data2
20//output of data3
21//file has been written 😁
 node  javascript  es6
Factorial↠ ↞Intro to Node - 2