New features in Node.js

 What I learned: Some new handy features in Node.js



1) fetch

Fetch API comes pre-built as of Node V.21! This means we don't have to install any additional packages to use this outside of browser environments. Less dependencies is always better in the long run, not only because the third party library is maintained by who knows but if you need to update Node in the future, a lot of your packages might not be compatible with the newer Node.

fetch('http://yourUrl')
.then(res=>res.json())
.then(data=>console.log(data))


2) try catch

Before if you needed to do some async calls and handle it, you had to do some acrobatics to perform async await...For example, you had to setup a function, then invoke it...

const fetchData = async () => {
const response = await fetch('http://yourUrl')
const data = await response.json()
console.log(data)
}
fetchData()

Now you can simply use try catch like this which makes it simpler.

try{
  const response = await fetch('http://yourUrl')
  const data = await response.json()
  console.log(data)
}catch(err){
  console.log(err)
}

3) watch

We don't really need nodemon anymore. When you make changes to your code, the nodemon package will automatically restart your node app. But now watch can do that same function out of the box.

In your package.json, setup your script like this:

  "scripts": {
    "watch": "node --watch server.js"
  },

Now when you run 'npm run watch', it'll restart whenever you make changes to your code.


Comments

Popular posts from this blog

Lifecycle of React components

Styled Components

e-commerce website built with React.nodejs