Function call in external file in NodeJS

0

I previously had a single file named aaa.js where the following code part existed, and separated in parts:

const callback = (err, data, res) => {
    if (err) return console.log('ERRO: ', err);
    res.writeHead(200, {'Content-Type': 'application/json'});
    return res.end(JSON.stringify(data));
};
const getQuery = (reqUrl) => {
    const url_parts = url.parse(reqUrl);
    return querystring.parse(url_parts.query);
};
const find = (req, res) => {
    const query = getQuery(req.url);
    MeuObjeto.find(query, (err, data) => callback(err, data, res));
};
const CRUD = {
    find
};
module.exports = CRUD;

After sorting codes to organize better, I created four different files as follows:

aaa.js

const find = require('./../actions/action-find')(MeuModel);
const CRUD = {
    find
};
module.exports = CRUD;

find.js

module.exports = (MeuModel) => {
    return (req, res) => {
        const query = getQuery(req.url); // <========= Como fica essa chamada?
        MeuModel.find(query, (err, data) => callback(err, data, res)); // <========= Como fica essa chamada?
    };
};

callback.js

module.exports = (err, data, res) => {
    if (err) return console.log('ERRO: ', err);
    res.writeHead(200, {'Content-Type': 'application/json'});
    return res.end(JSON.stringify(data));
};

get-query.js

module.exports = (reqUrl) => {
    const url_parts = url.parse(reqUrl);
    return querystring.parse(url_parts.query);
};

DOUBT : How do I call the "callback" and "get-query" functions from within the "find.js" file as pointed out in the code comment?

    
asked by anonymous 19.05.2017 / 23:21

1 answer

0
const query = require('get-query')(url);
let callback = require('callback')(err, data, res);
MeuModel.find(query, (err, data) => callback;

When you want to call another file you use require with its name (without .js as it is calling the module), and pass the parameter that is used in the function of the other file in the next parentheses.

As functions can be stored in variables, from a require in the function and pass it after the callback, that second case is not 100% sure (if someone can confirm with a thankful comment)

    
19.05.2017 / 23:51