-1

I have "global" variable that can be called all over my nodejs program. I just want to wrap my response object into "global" variable.

i can render with this:

http.createServer(function (request, response) {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end('Hello World\n');
}).listen(8081);`

but with this not:

global.render : function(res,result){
  **res.writeHead(200,{'Content-Type': 'text/plain'});**
  res.end(''+ result);
}

Using;

global.render(res, 'this just in html');

This bold row gives me an error. Cant figure it out?

Ivan Beldad
  • 2,285
  • 2
  • 21
  • 33
  • 3
    Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. – baao Apr 20 '18 at 19:53
  • Also worth reading: [Why are global variables considered bad practice?](https://stackoverflow.com/questions/10525582/why-are-global-variables-considered-bad-practice) – baao Apr 20 '18 at 19:53
  • better quit using `http` package when You're going to make something big (: switch to any http framework: `connect`, `express`, `sails`, `koa` and delete Your question, it's tells about lack of JS knowledge – num8er Apr 20 '18 at 20:51

1 Answers1

0

Avoid using globals.

You may get in situation when some code can replace Your global variable/function/class.

So just make it like a module:

lib/render.js

module.exports = (res, body) => {
  res.writeHead(200,{'Content-Type': 'text/plain'});
  res.end(body);
}

and use it in Your code:

const render = require('./lib/render');

http.createServer((request, response) => {
    if (request.url === '/') {
      return render(response, 'Hello World');
    }
    render(response, 'URL: '+request.url);
}).listen(8081);
num8er
  • 18,604
  • 3
  • 43
  • 57