I have a node server which serve the response(.js file)along with other details to client.I want that it should send the .js file once.In client side the .js file should save in cache. So when ever request came to server if there already cache available for that .js file it should not download it again. For this I am facing high CPU usage.
Thanks in advance.
You can serve static files (html, css or js) with express by using express.static, pointing to a folder in your project, like this:
app.use(express.static(__dirname + '/public'));
See this link for more information: http://blog.modulus.io/nodejs-and-express-static-content
The browser should do this caching work for you, but it seems you need to implement this by yourself. If you still need to implement your own cache, take this into account:
For the first issue, I suggest to use browser side persistence, I do not recommend using localStorage, cookie or similar since it is not 100% cross-browser, instead , I do recommend using shims like persist.js https://github.com/jeremydurham/persist-js
To address the second problem, I suggest using IDs for the files, these IDs can be computed on server side from content (using SHA digest), this would allow you to change the JS file when needed (identity based on content, like GIT)
For example, you can do this
store = new Persist.Store('My Application');
function loadCachedJs(sha, loadedCallback) {
var jsCode = store.get(sha);
if (jsCode) {
// the js is on cache!, you can load it without going to server
setTimeout(
function() {
eval(jsCode);
loadedCallback();
}
);
} else {
// the js is not on cache, you need to go to server
// but is only for this first time
$.get("/.../.../" + sha + ".js", function(res) {
// store the result on cache
storeJsOnCache(sha, res.data);
eval(res.data);
loadedCallback();
});
}
}
function storeJsOnCache(jsCode) {
store.set(sha, jsCode);
}
Then, on certain section of your code, you get "load the js file of certain sha", you call loadCachedJs:
...
loadCachedJs(sha, function() {
// JS loaded, do what you need to do with this js file
});
And, on server side, you will need to implement the endpoint returning the JS corresponding to SHA