Gabriel M Fernandes Gabriel M Fernandes - 6 months ago 17
Node.js Question

Calling methods from other files with Node.js

I'm failing to require methods from my

./db/index.js
into my
server.js
file to select data from the database and display it.

The
/db/index.js
is like this:

'use strict';

const pgp = require('pg-promise')();
const pg = pgp(process.env.DATABASE_URL);

let select = () => {
pg.any('SELECT username, status FROM status')
.then(function(data){
for (var item of data) {
return item.username + "'s status is " + item.status;
}
})
.catch(function(err) {
return 'Error: ' + err.message || err;
});
};

module.exports = () => {
select
};


and I want to call it in from a different file:

'use strict';

const port = process.env.PORT || 3000;
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const db = require('./db/');

app.use(bodyParser.urlencoded({extended: true}));

app.post('/logdash', function(req, res, next) {
res.status(200).send(db.select());
});

app.listen(port, function() {
console.log('Server is running on port', port);
});


I'm using Heroku, and like this, watching the logs, no error is shown in both terminal and Slack (it's a slash command). I can't find help on how to properly separate the functions. How can I call this
select
method and any other one from a different file?

Answer

There are many problems in your code, some of them listed in the previous answer by @jfriend00.

I will only add that you also do not return any data from the method when it is successful.

Considering how many errors you got there, rather than re-iterating them, I will give you a corrected code example instead.

The database module:

'use strict';

const pgp = require('pg-promise')();
const db = pgp(process.env.DATABASE_URL);

let select = (req, res, next) =>
    db.map('SELECT username, status FROM status', null, row=> {
        return row.username + "'s status is " + row.status;
    })
        .then(data=> {
            res.status(200).send(data);
        })
        .catch(err=> {
            res.status(500).send(err.message || err);
        });

module.exports = {
    select
};

And the server file:

'use strict';

const port = process.env.PORT || 3000;
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const db = require('./db/');

app.use(bodyParser.urlencoded({extended: true}));

app.post('/logdash', db.select);

app.listen(port, function () {
    console.log('Server is running on port', port);
});

The code is based on pg-promise v.4.3.x (upgrade, if you have an older one).

I wouldn't say it is a good approach to organizing your code, but at least it is a working example. You can check out pg-promise-demo for a complete application example that may give you a better idea of how to organize your database code.

Comments