Node – Array not emptying

Solution for Node – Array not emptying
is Given Below:

I’m with a scraping project.

When I scrape from a site all the data goes to a JSON, the problem is when I scrape another info the JSON contains the old info + the new one. At the begining I set a data = [], but is not working.'/scraping', function(req, res) {

    (async () => {

        try {

            data = [];

            response = await requestPromise(req.body);
            $ = cheerio.load(response);
            $('div#all > img').each(function() {
                let img = $(this).attr('data-src');
                    imgURL: img

            data = JSON.stringify(imgs);
            fs.writeFileSync('chapter.json', data);

        } catch (e) {


It seems like your data variable is a global, or defined somewhere out of scope. That means that the data “reference” is the same between all calls.

Declare data within your function, i.e. let data = [];.