How to split code into multiple modules?

Asked

Viewed 940 times

6

I know that it is possible to separate functions into other files on Node, called modules, as follows:

js server.

var http = require("http");
var servidor = http.createServer();
var porta = 3000;

var corpo = require("./modulo-corpo.js");

servidor.on("request", function (request, response) {
    var resposta = corpo.getCorpo();
    response.writeHead(200, {
        "Content-Type": "text/plain",
        "Content-Length": resposta.length
    });
    response.end(resposta);
});

servidor.listen(porta, function () {
    console.log("servidor da bete, rodando na porta " + porta);
});

modulo-corpo.js

var n = 0;
exports.getCorpo = function() {
    return "bete beijou " + ++n + " bebados barrigudos bebendo bebidas baratas";
}

I would like to know what resources are available for code organization on the Node.

A practical example of what I imagine would be to access the variable n body module, as if it had been declared in the file servidor.js.

The intention is to organize the code, making, for example, a module only with variables, another only with routes, etc., so that it is easier to be treated/changed/expanded in the future.

1 answer

4


The way the n is inaccessible to other modules and n behaves as private variable module. This is very useful in many cases.

If you want to consult the n you have to make a getter that could be so:

var n = 0;
exports.getCorpo = function() {
  return "bete beijou " + (++n) + " bêbados barrigudos bebendo bebidas baratas";
}
Object.defineProperty(exports, 'n', {
  get: function() {
    return n;
  }
});

So the module gets a property n that will fetch the real value of n cannot be overwritten.

If you want to manipulate n you can do a Setter too:

Object.defineProperty(exports, 'n', {
  get: function() {
    return n;
  },
  set: function(valor) {
    n = valor;
  }
});

I made an online example that you can download and test (link). The idea is:

file: server.js

const http = require('http');
const express = require('express');
const app = express();
const variaveis = require("./variaveis");
const rotas = require("./rotas")(app);

const server = app.listen(process.env.PORT || 3000, function(){
    const host = server.address().address;
    const port = server.address().port;
    console.log('App listening at http://%s:%s', host, port);
});

file: variables.js

let contador = 0;

const variaveis = Object.create(Object.prototype, {
  carregamento: { // data em que o servidor começou a correr
    writable: false,
    configurable: false,
    value: new Date() 
  },
  contador: {
    configurable: false,
    get: function() { return contador++ },
    set: function(valor) {
      contador = valor;
    }
  }
});

module.exports = variaveis;

file: routes.js

const variaveis = require("./variaveis");
module.exports = (app) => {
    app.use('/', (req, res) => {
       res.end('O contador esta em: ' + variaveis.contador); 
    });

    app.use(function(req, res, next){
        console.log(req.originalUrl);
    });
}

With this structure it is possible for any file to know the value of contador as well as changing its value outside the file where that variable is inserted.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.