Home Application-scope Variables in Node.js?
Reply: 1

Application-scope Variables in Node.js?

JRomeo Published in 2017-11-14 19:07:51Z

Is there a variable scope in Node.js that persists longer than the request, that is available to all application users? I'd like to create a variable that can be read/written to by multiple app users, like so:

var appScope.appHitCount += 1;

The session scope won't work because it is user specific. Looking for application specific. I couldn't find anything in the Node.js docs. Thanks.

Mark_M Reply to 2017-11-14 19:23:07Z

If you have a variable scoped to the app module it will be available and shared by everything within the scope. I imagine in a big app you would need to be careful with this, but it's just regular javascript scoping. For example this will continue to append to the array as you hit it:

const express = require('express')
const app = express()
var input = []

app.get('/:input/', (req, res) => {
    var params = req.params
    res.send("last input was: " + JSON.stringify(input))

app.listen(8080, () => console.log('Example app listening on port 8080!'))

Now visiting 'http://localhost:8080/hi' returns:

last input was: ["hi"]

and then 'http://localhost:8080/there' returns:

last input was: ["hi", "there"]


If you want something shared by the entire app (i.e. all the modules) you could set up a module that is require()d by all the modules and i=has the responsibility of getting and setting that value.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.407138 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO