Node requests and module Exports

Asked

Viewed 170 times

0

Good afternoon guys. Someone can answer a question for me. I have a Node.js application with an estr

//index.js
var express = require('express');
var app = express();

var valor = require('./valor');

app.get('/:valor', function (req, res) {
  valor.setValor(req.param.valor);
  ...
  console.log(valor.getValor());
  ...
  res.send(valor.getValor());
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});


//valor.js
let meuValor = null;
async function setValor(valor) {
  meuValor = valor;
}

async function getValor() {
  return meuValor;
}

module.exports = {
  setValor,
  getValor,
};

If I have a series of simultaneous requests each one will get the return sent in the request, or this class value.js it is global in the service. and one ends up taking from the other.

  • I think that, in the way that your class/object was built, it will be the global value.

  • And there’s a way I can make it not global?

  • If you create as an instance, yes... Something like valor = new Valor for each request.

  • I get it, but do I need to use this object within another class to regain its value like I would? Type if within my app.get('/:value', Function (req, res) {} I called another controller file to process the request, as I would to recover that value without going through parameter.

No answers

Browser other questions tagged

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