Hello! I would like to know if in nodejs it is possible to separate some codes in different files as in this example below, and how to do this:
I currently only have one file this way:
File 111.js
var app = require('../app');
var debug = require('debug')('cancela:server');
var http = require('http');
var b = require('../config/gpio');
const bbbio = require('../config/bbb-io');
// Códigos iniciais
//...
//...
var server = http.createServer(app);
// Códigos para serem separados em outro arquivo
var io = require('socket.io').listen(server);
io.on('connection', function (socket) {
socket.on('changeState', handleChangeState);
});
function handleChangeState(data) {
var newData = JSON.parse(data);
b.digitalWrite(bbbio.controleCancela, newData.state);
}
// Outros códigos
//...
//...
Creating an additional file "functions.js"
functions.js
var io = require('socket.io').listen(server);
io.on('connection', function (socket) {
socket.on('changeState', handleChangeState);
});
function handleChangeState(data) {
var newData = JSON.parse(data);
b.digitalWrite(bbbio.controleCancela, newData.state);
}
And including "functions.js" in "111.js" to get something like below, but I can not find the right way to "include" or "require":
111.js already updated:
Arquivo 111.js
var app = require('../app');
var debug = require('debug')('cancela:server');
var http = require('http');
var b = require('../config/gpio');
const bbbio = require('../config/bbb-io');
// Códigos iniciais
//...
//...
var server = http.createServer(app);
require('./functions'); <<<=== APENAS INCLUIR O CONTEÚDO DO ARQUIVO functions.js, SUBSTITUINDO O CÓDIGO ANTERIOR, MAIS NADA
// Outros códigos
//...
//...