Node JS Basics :)
Tags: javascript, webdev, programming, tutorial
Published: 2023-01-02 16:22:33

## Difference between running JavaScript in Browser and Node JS

In the Brower if you do a right click and go to inspect 

You will find the console where  if we write window , we could see window object with different properties or method such as setTimeout() , setInterval() so we just have to write property name to use it. So the window object is global in the browser.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s3cw220owol3d4xegozy.png)


But in Node JS, we have global object with the keyword global so if we 

console.log(global)

we get

 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wnarac99kvo6g5hym6y2.png)


now we write 

```jsx
global.setTimeout(() =>{
    console.log('in the timeout')
},3000)
```

we will get the desired output but since global is Global object so we don’t have to write global explicitly. 

Two useful properties

```jsx
console.log(__dirname) 
// absolute path of the current folder without current file 
console.log(__filename) 
// absolue path of the current folder with the current file
```

We can’t access DOM such as querySelector in global object in node.

## Module and require  

In text.js

```jsx
const fruits = ['apple','mango','oranges','guava'];

console.log(fruits)
```

create a new JS file  let say module.js and type

```jsx
const xyz =  require('./text');

console.log(xyz)
```

it will give you result as 

**[ 'apple', 'mango', 'oranges', 'guava' ]
{}**

xyz as no return value but if we add

```jsx
const fruits = ['apple','mango','oranges','guava'];

console.log(fruits)

module.exports = fruits
```

then xyz will return
[ 'apple', 'mango', 'oranges', 'guava' ]

Another case would be if you want to export multiple values then

```jsx
const fruits = ['apple','mango','oranges','guava'];
const age  = [1,2,3,4,5]
console.log(fruits)

module.exports = {
    fruits,
    age
}
```

now in module.js

```jsx
const xyz =  require('./text');

console.log(xyz.age)
```

we also destructure it 

```jsx
const {people,age} =  require('./text');

console.log(age)
```

Node JS also contains core module such as OS, file system(fs) , etc.

```jsx
const os = require('os')
console.log(os.homedir())
```

 

## File System (fs)

It is used to handle files and perform operations such as reading, writing, deleting etc.

To import this

**`const** fs = require('fs');` 

or 

Destructure this

`const {readFile,writeFile} = require('fs');`

using this you don’t have to use ‘fs’ as a prefix before a method

→ Reading files

```jsx
fs.readFile('./docs/path.txt',(err,data)=>{
  if(err)
  {
    console.log(err);
  }
  console.log(data);
})
```

this will give a buffer <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>

*Buffer is just a package of data that has been send towards when we read this file*

so we have to convert data into string 

```jsx

  console.log(data.toString());
```

Also they are asynchronous means *can start long-running tasks, and continue running other* tasks in parallel**.**

→ Writing files

```jsx
fs.writeFile('./docs/path.txt', 'hello , everyone' , () =>{
    console.log('file is wriiten');
})
```

It will overwrite the text in the file 

→ Directories

```jsx
if(!fs.existsSync('./assets')){ 
fs.mkdir('./assets',(err) =>{
    if(err){
        console.log(err);
    }
    else{
        console.log('folder created');
    }
})
}
else{
    fs.rmdir('./assets',(err) =>{
        if(err)
        {
            console.log(err);
        }
        console.log('folder deleted')
    })
}
```

if the directory doesn’t exists then it will be created using mkdir else it will be deleted using rmdir.

→ deleting files

```jsx
//deleting files
if(fs.existsSync('./docs/delete.txt'))
{
    fs.unlink('./docs/delete.txt',(err) =>{
        if(err)
        {
            console.log(err);
        }
        console.log('file deleted')
    })
}
```

we use unlink method to delete the files

## Streams and buffers

Now imagine we have a large data or file, we could wait for the file to be read completely but that could take a long time. We could pass the data in a bit of a Stream i.e. a small chunk of data that is known as a buffer and send down the stream every time a buffer fills so that you can start using the data. It is used for such as video loading.

Two types 

Read streams and write streams

 firstly,

```jsx
const fs = require('fs');

const readStream = fs.createReadStream('./docs/path.txt', { encoding : 'utf8'});
const writeStream = fs.createWriteStream('./docs/path.txt',{flags : 'a'});
```

 

```
readStream.on('data',(chunk) =>{
     console.log('---New Chunk----');
     console.log(chunk);
     writeStream.write('---New Chunk----');
     writeStream.write(chunk);
 })
```

on is a event listener to listen to the buffer of data. ‘data’ is an event in this situation like ‘click’. In the above code after reading the buffer, it rewrites the buffer with 'writeStream'. To make the process short, we can just write*

*`readStream.pipe(writeStream)`*

that s it !🙂

**reference** - net ninja(youtube), coding addict(youtube), google search