Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Node.js – How to pass a value to another file

I have a project in which I use Express.js and activedirectory package for LDAP authentication.

I have a file called ad.js which includes-

exports.authUser = (username, password) => {
    ad.authenticate(username, password, function (err, auth) {
        if (err) {
            console.log('ERROR: ' + JSON.stringify(err));
            return;
        }
        if (auth) {
            console.log('Authenticated!');
        } else {
            console.log('Authentication failed!');
        }
    })
}

I call authUser in app.js-

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

app.post("/login", (req, res) => {
  let username = req.body.username;
  let password = req.body.password;
  authUser(username, password);
})

The authentication works but I want to access the value of auth in app.js.
What is the correct way to perform that?

Thanks for any advice.

>Solution :

You can "promisify" your function and then await for the result. The main function returns a promise object and the route awaits for that promise to resolve.

exports.authUser = (username, password) => {
    return new Promise((resolve, reject) => {
        ad.authenticate(username, password, (err, auth) => {
            if (err) {
                console.log(`ERROR: ${JSON.stringify(err)}`);
                return reject(err);
            }
            console.log(auth ? 'Authenticated!' : 'Authentication failed!');
            return resolve(auth);
        });
    });
};

app.post("/login", async (req, res) => {
    const username = req.body.username;
    const password = req.body.password;
    try {
        const auth = await authUser(username, password);
    } catch (error) {
        // do something
    }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading