M.Ramzan M.Ramzan - 2 months ago 19
Node.js Question

Global variable doesn't get initialized nodejs

I have two javascript files. For simplicity I have created routers and I want to maintain one variable and change its value across all files, something similar to java's static fields. but the variable I want to initialize doesn't get initialize.

Like in the server.js file I have Vmessages variable I want to make it something similar to java's satic variable so I can change its value in another file and access the changes in server.js file. This is server.js file,

//server.js file

var Vmessages = [{text: 'some text', owner: 'Tim'},{text: 'other message', owner: 'Jane'}];

app.get('/messages', (req, res) => {
res.json(Vmessages);
});

module.exports.variableName = Vmessages;

app.use(require('./routes/messages'));


So I have imported the server.js files Vmessages variable and change its value in messages.js file. As you can see in the code snippet below i can access the server.js file's variable and make changes. And even when I print it it shows changes are made. But when I access the Vmessages in server.js file its value didn't change and it was in its initial value.

//messages.js file

var sourceFile = require('../server.js');
var messages = sourceFile.variableName;

router.post('/messages', (req, res) => {

console.log(sourceFile.variableName); //[{text: 'some text', owner: 'Tim'}]

messages.push({text: 'other message', owner: 'Jane'});

console.log(sourceFile.variableName); //[{text: 'some text', owner: 'Tim'},{text: 'other message', owner: 'Jane'}]

res.json(req.body);
})

module.exports = router;


Where am mistaken this?

Answer Source

@M.Ramzan use this code . I made some changes to routes code. This works as per your requirement. Here server.js file

var express = require('express');
var app = express();

var variableName;
var Vmessages = [{text: 'some text', owner: 'Tim'},{text: 'other message', owner: 'Jane'}];

app.get('/messages', (req, res) => {
   res.json(Vmessages);
});

exports.variableName = Vmessages;

app.use(require('./routes/messages'));

app.listen(3000,function(){
    console.log("Server listening on 3000");
});

Here is messages.js file

//messages.js file
var express = require('express');
var bodyParser = require('body-parser');
var sourceFile = require('../server.js');
var app = express();
var messages = sourceFile.variableName;
var router = express.Router();
router.use(bodyParser.json());

router.post('/messages', (req, res) => {

console.log(sourceFile.variableName); 
messages.push(req.body);
res.json(messages);
});

module.exports = router;

Run the serevr as node server.js. And you can get the data in Vmessages as http://localhost:3000/messages using get method. And you can add data to Vmessages using http://localhost:3000/messages using post method. You can add data by using request body. Hope this helps.....