简体   繁体   中英

How to turn a query result into a js variable (Javascript)

I've been searching for this for a day now and I'm basically hopeless. All I want to do is export the query result as a string (so dataString basically) so I can import as a string in my external .js file.

module.exports.getKlanten = function(req, res){
console.log("zoekt naar klanten");
pool.connect(function(err, client, done){
    if(err){
        return console.error('error fetching client from pool', err);
    }
    client.query("select * from abc.relations limit 5", function(err,result){
        done();
        if(err){
            return console.error('error running query', err);
        }            
        var dataString = JSON.stringify(result.rows);
        var count = Object.keys(result.rows).length;

        var klanten = result.rows;

        res
        .status(200)            
        .render("index", {dataString: dataString, klant: klanten, count: count});        

    console.log("done");
    })        
});

}

And what would I have to do in the js file to import the string then? It looks so easy yet I can't seem to get it right.

It would be something like this

module.exports.getKlanten = function(req, res){
console.log("zoekt naar klanten");
return "Hello world"; }

and then in your external .js file, you can import it like this

const myModule = require('./JSFile');

and use it like this

console.log(myModule.getKlanten());

Also, use a return statement so that you have a string in your variable.

I am assuming that you need to use the same function externally somewhere else and also for http handler so split it into three files.

 //getKlanten.js module.exports.getKlanten = function(){ return new Promise(function (resolve, reject) { pool.connect(function(err, client, done){//make sure pool is avialble here if(err){ console.error('error fetching client from pool', err); reject(err); } client.query("select * from abc.relations limit 5", function(err,result){ if(err){ console.error('error running query', err); reject(error); } var dataString = JSON.stringify(result.rows); var count = Object.keys(result.rows).length; var klanten = result.rows; var data = {dataString: dataString, klant: klanten, count: count} resolve(data); }) }); }) } //in external.JS var getKlanten = require('getKlanten'); getKlanten().then(function(object) { console.log(object); }, function(err){ console.log(err); }) //in http handler file var getKlanten = require('getKlanten'); module.exports = function(req,res) { getKlanten().then(function(data) { res .status(200) .render("index", data); }); } 

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