简体   繁体   中英

Fs not saving file correctly and how to simplify this code

So I want to save the titles array formatted with line breaks and index of each element.

When I save the 'formatted' object with fs all I get in the file is 'undefined'.

Also, this code is probably really messy and could be simplified, what should I change?

            const $ = cheerio.load(body);
            let titles = [];
            $('div.collection.clearfix').each((i, el) => {
                const title = $(el)
                    .text()
                    .replace(/\n/g, '')
                    .trim()
                    .replace(/ /g, ',');
                titles.push(title);
            })

            let formatted = titles.forEach((i, title) => {
                return title + '. ' + i + '\n'
            });
            fs.writeFile('titles.txt', formatted, (e) => {
                if (e) console.error(e)
            })

You expect

            let formatted = titles.forEach((i, title) => {
                return title + '. ' + i + '\n'
            });

to return an array.

However, forEach returns undefined .

You are looking for titles.map , which returns an array. Then, you can join all the elements using Array.prototype.join() to turn it into a single string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM