What is an optimal way of not repeating myself in the following code? Following code works and i am simply looking for ways to not repeat myself as well keep to code clean and readable. Would love to see what methods that can be utilized to make it prettier.

const util = require("util");
const fs = require("fs");
const reader = util.promisify(fs.readFile);
const simpleParser = require('mailparser').simpleParser;

async function readFile(filepath) {
    try {
        return await reader(filepath)
    } catch (err) {
        return err
    }
};

async function getAttachment(filepath) {
    let file, email;
    try {
        file = await readFile(filepath);
    } catch (err) {
        return err
    }

    try {
        email = await simpleParser(file)
        return email.attachments[0].content.toString()
    } catch (err) {
        return err
    }
}

async function getFileName(filepath) {
    let file, email;
    try {
        file = await readFile(filepath);
    } catch (err) {
        return err
    }

    try {
        email = await simpleParser(file)
        return email.attachments[0].filename.toString()
    } catch (err) {
        return err
    }
}



async function main() {
    let attachment = await getAttachment('./mock-data/google-report.email')
    let filename = await getFileName('./mock-data/google-report.email')
    console.log(filename)
}


main()

module.exports = {
    getAttachment
}
DRY review

You don't need to wrap try catch around async function or promise. The errors will all get passed onto the final promise.catch. So can remove all 5 try catches.

The function readFile is just wrapping a promise and is completely redundant.

The two functions getAttachment and getFileName are almost identical apart from the final return.

The two file loads are of the same file that need only be done once.

filePath as a string is defined twice, again only once is best.

All you want is attachments[0] of the one email. So you don't need to store file and email.

You use util.promisify and fs.readFile only once so no need to hold a reference for either.

Assigning the variables attachment and filename can be done via destructuring saving another token.

You are creating a module so keep variable names short, use the context to infer meaning.


The end result is
const reader = require(&quot;util&quot;).promisify(require(&quot;fs&quot;).readFile);
const parser = require('mailparser').simpleParser;

async function main(file) {
    const atts = (await parser(await reader(file))).attachments[0];
    const [attachment, filename] = [atts.content.toString(), atts.filename.toString()];
    console.log(filename);
}
main(&quot;./mock-data/google-report.email&quot;).catch(err =&gt; /*do something with error*/ );