1
Hello! I wonder if in nodejs it is possible to separate some codes in different files as this example below, and how to do this:
Currently I have only 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 "functions.js file"
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 look like below, but I’m not finding the right way to do "include" or "require":
111.js 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
//...
//...
Lucas and @Notme, thank you. I ended up not commenting ,but I had already checked the documentation in addition to other staff posts and found these features. What I would really like is for the code to be replaced, literally, from the contents of the separate file
foobar.js
into themain.js
, not to have to call the exported functions as inconsole.log(bar());
.It would be the equivalent of what a "DEFINE" does in "C language". It is possible this in Nodejs or I am traveling?– wBB
@wBB does not give, the Node method is require + module.exports. The module system was designed so as not to leak anything pro global scope.
– bfavaretto