node.jsldapjs

Data from LDAP query in variable LdapJS


I'm trying to get the data from LDAP and I'm getting it successfully but it's not written into variable so then after the code is executed I can make some checks on the data.

var server = LdapJS.createClient({
    url: LdapConf.server.url,
    tlsOptions: LdapConf.server.tlsOptions
});
server.bind(LdapConf.server.bindDN, LdapConf.server.bindCredentials, function(err) {
    if (err) {
        return done(err);
    }
});
var SearchOtps = {
    filter: '(uid=' + username + ')',
    scope: 'one',
};


var UserSearch = server.search(LdapConf.server.searchBase, SearchOtps, function(err, res) {
    res.on('searchEntry', function(entry) {
        console.log('entry: ' + JSON.stringify(entry.object));
        return (JSON.stringify(entry.object));
    });
    res.on('searchReference', function(referral) {
        //console.log('referral: ' + referral.uris.join());
    });
    res.on('error', function(err) {
      //console.error('error: ' + err.message);
    });
    res.on('end', function(result) {
      //console.log('status: ' + result.status);
    });
});

console.log(UserSearch);

I just do not know how to stop further code execution while it's waiting for the return of the LDAP search.

Server Started
undefined

Solution

  • You could do a function that returns it in promise.

    function UserSearch(server,LdapConf, SearchOtps) {
      return new Promise(function(resolve,reject) {
    
        server.search(LdapConf.server.searchBase, SearchOtps, function(err, res) {
            res.on('searchEntry', function(entry) {
                console.log('entry: ' + JSON.stringify(entry.object));
                resolve(JSON.stringify(entry.object)));
            });
            res.on('searchReference', function(referral) {
                //console.log('referral: ' + referral.uris.join());
            });
            res.on('error', function(err) {
              reject()
            });
            res.on('end', function(result) {
              //console.log('status: ' + result.status);
            });
        });
      }
     }
     
     UserSearch(server,LdapConf, SearchOtps)
     .then(function(res) {
       console.log(res)
     })