Include or Require on Nodejs to separate codes

1

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
//...
//...
    
asked by anonymous 20.07.2017 / 23:59

2 answers

2

The requires part is correct, but within each module you need to export the parts to be public. For example:

file1.js

function funcao() {

}
exports.funcao = funcao;

file2.js

var funcoes = require('./arquivo1.js');
funcoes.funcao();

This article gives more details: link

    
21.07.2017 / 00:05
0

With ES6 the syntax is different and can provide some other functionality, as the import is asynchronous and can only import parts that are required.

Syntax

foobar.js

export function foo() {
  return 'bar';
}
export function bar() {
  return 'foo';
}

main.js

import {foo, bar} from 'foobar';
console.log(foo());
console.log(bar());
    
21.07.2017 / 00:26