Is there some sort of Session-like variable to hold an array in Nodejs? What I meant is like something where I can define the name in other scope and be accessed in different scope (i.e: Variable("Array1") is defined in function A but accessed in function B and persists until it is destroyed).
The reason is I am using Meteor for slicing big files into small blobs and pass it back the chunk to the server. I tried to use the combination of fs.WriteFile
and fs.AppendFile
but somehow the file is mutilated along the way (the file is a video and playback error occurred with the copied file).
I read somewhere that blob can be rebuild by the constructor. However, I would need to pass this to a global or session-like variable in order to do so.
So...how can I use such thing in Nodejs?
There is such thing – it is called database :-)
When you're in Meteor, all files are loaded to a single running environment. Therefore, unlike in plain Node, a global variable created in one file can be accessed in any other one. So you can write
Slices = {};
in one file, and then in another say
Slices['Array1'] = ...
Notice there is no var
keyword when defining the Slices
object, otherwise it wouldn't be global but scoped to the file.
There is obviously one problem with the above method, and it's persistence over server reload. When the server crashes and restarts, or when you upload a new version, all such variables are recreated and you lose your data.
To prevent this, you need to store your variables in a place where they are retained permanently – a database of some kind. There are several solutions tailored for such runtime variables (such as Redis), but since you're using Meteor the natural solution would be to use the provided Mongo database. So just create a new collection on the server side
Slices = new Meteor.Collection('slices');
and use the usual find
, insert
, update
and remove
methods to access your variables.
If everything happens in the same process space, you can use a module as a singleton.
Remember, even if a module is included multiple times, the same copy is returned.
So if you have this module:
module.exports = new Array();
And you include it by several other modules, each one of them will have the same array instance.
You can also have a more complex singleton:
var blocks = {};
module.exports.addBlock = function(name, block) {
blocks[name] = block;
};
module.exports.getBlock = function(name) {
return blocks[name];
};
module.exports.delBlock = function(name) {
delete blocks[name];
};
module.exports.list = function() {
return Object.keys(blocks);
};
In your different files, you would include and use this module like:
var blocks = require('./blocks');
console.log(blocks.list());
Read about module caching here.