Use same JS file for front end and nodeJS

Lets say you have some front end logic function placed in one of the .js files and it gets executed in browser. What if you want to reuse the same logic in your nodeJS back end code. It's not straight forward to reuse the same function in nodeJS even though its powered by the same javascript engine.

Here are few ways where you can reuse the same piece of code for nodeJS backend:

a) Execute the js file in current context

var fs = require("fs");
var vm = require('vm');
var content = fs.readFileSync("filename.js")

Above commands runs the compiled code present in filename.js and returns the result.

b) Make each function/file as global variable method:

We will code our front end logic in nodeJS convention but slightly modify it so that it works out of box in browsers.

Make sure you adapt the entire code as per nodeJS convention like :

exports.fn_name= function()


Paste the below lines at start of each js file having your function :

if(typeof global == 'undefined'){
var exports = this['frontend_logic'] = {};

This checks whether we have a global object.

If we execute this from nodeJS , we always have this object. In case of front end browser execution, global will be undefined. Since we wont have 'exports' object in front end execution, we create a dummy one and create a method for each file. In this case it will be frontend_logic.

Usage of the function in nodeJS :

frontend_logic= require("frontend_logic.js");

Usage in normal JS files :

About This Blog

There is something for everyone. !! A tech blog on various topics. Let it be devops, programming etc; we have it all covered here in layman terms :)

Total Pageviews

Back to TOP