Menu

ReferenceError: fetch is not defined

If you are seeing this error while using the node that means your node version doesnt support out of the box fetch API. There could be two possible solution

1. Upgrade the node version

Check installed node version using command >> node -version

Then using this command update node version to latest node version. npm install -g node

2. Install node-fetch

You could use the fetch with your existing project and node version as well. For that you have to install the node-fetch and use it.


a). Node install command
npm install node-fetch@2

b). After successful install create a fetch constant in your JS file where you are usign the fetch. Like below.

const fetch = require("node-fetch");

Code Quality Rules in AEM Cloud Manager

Sonar code quality rules in Adobe cloud manager








Callback function JavaScript and NodeJS

Lets understand the callback fucntion in NodeJS using the below geocode example.

Here we have created geoCode function with two paramters, first parameter will take input of the location name and second parameter the function that needs to call. Similary, we can add or pass any number of paramters in fucntion as per need.

const geoCode = (location, callback) => {
    const data = {
        location: location,
        latitude: 0,
        longitude: 0
    }
    callback(data)
}

 

When we call the geoCode function, we are here passing a city name and second paramter a fucntion itself that print the return data from callback on console.
 
geoCode('New Delhi', (callbackData) => {
    console.log(callbackData)
});

Return

{ location: 'New Delhi', latitude: 0, longitude: 0 }