JavaScript , Inquirer : Getting an error for user defined Imported function

21 Views Asked by At

The below program is taking the CLI input from the user and is printing to the text file.

**Question **: the program is giving an error when passing the user promise "result" to the imported user defined function "writeFile" as "writeFile" is not a function . But it's working fine if the exported function is written as module.exports={writeFile} instead of this module.exports=writeFile in page-write.js file .Please advise why it is happening like this .

app.js file

const inquirer = require('inquirer');
const {
    writeFile
} = require('./utils/page-write');

const userInput = () => {
    return inquirer.prompt([{
        type: 'input',
        name: 'userName',
        message: 'What is your name?',
        validate: (name) => {
            if (name) return true;
            else {
                console.log("Input your name");
                return false;
            }
        }
    }, {
        type: 'rawlist',
        name: 'communication',
        message: 'What is your preferred method of communication?',
        choices: ['homephone', 'email', 'mobile'],
        default: 1
    }])
}

userInput().then((result) => {
    console.log(result);
    return writeFile(JSON.stringify(result));
}).then(writeFileResponse => {
    console.log(writeFileResponse)
}).catch((err) => {
    if (err) {
        console.log(err);
    }
});

---------------------------------------------
page - write.js file

const fs = require('fs');

const writeFile = (userData) => {
    return new Promise((resolve, reject) => {
        return fs.writeFile('./index.txt', userData, err => {
            if (err) {
                reject(err);
                return
            }
            resolve({
                ok: true,
                message: "data is sucessfully written"
            })
        })
    })
}

module.exports = writeFile;
0

There are 0 best solutions below