DEV Community

Khushi
Khushi

Posted on

Node JS Basics :)

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

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

console.log(global)

we get

Image description

now we write

global.setTimeout(() =>{
    console.log('in the timeout')
},3000)
Enter fullscreen mode Exit fullscreen mode

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

Two useful properties

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
Enter fullscreen mode Exit fullscreen mode

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

Module and require

In text.js

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

console.log(fruits)
Enter fullscreen mode Exit fullscreen mode

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

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

console.log(xyz)
Enter fullscreen mode Exit fullscreen mode

it will give you result as

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

xyz as no return value but if we add

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

console.log(fruits)

module.exports = fruits
Enter fullscreen mode Exit fullscreen mode

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

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

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

module.exports = {
    fruits,
    age
}
Enter fullscreen mode Exit fullscreen mode

now in module.js

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

console.log(xyz.age)
Enter fullscreen mode Exit fullscreen mode

we also destructure it

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

console.log(age)
Enter fullscreen mode Exit fullscreen mode

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

const os = require('os')
console.log(os.homedir())
Enter fullscreen mode Exit fullscreen mode

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

fs.readFile('./docs/path.txt',(err,data)=>{
  if(err)
  {
    console.log(err);
  }
  console.log(data);
})
Enter fullscreen mode Exit fullscreen mode

this will give a buffer

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


  console.log(data.toString());
Enter fullscreen mode Exit fullscreen mode

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

→ Writing files

fs.writeFile('./docs/path.txt', 'hello , everyone' , () =>{
    console.log('file is wriiten');
})
Enter fullscreen mode Exit fullscreen mode

It will overwrite the text in the file

→ Directories

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')
    })
}
Enter fullscreen mode Exit fullscreen mode

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

→ deleting files

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

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,

const fs = require('fs');

const readStream = fs.createReadStream('./docs/path.txt', { encoding : 'utf8'});
const writeStream = fs.createWriteStream('./docs/path.txt',{flags : 'a'});
Enter fullscreen mode Exit fullscreen mode
readStream.on('data',(chunk) =>{
     console.log('---New Chunk----');
     console.log(chunk);
     writeStream.write('---New Chunk----');
     writeStream.write(chunk);
 })
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)