0

I'm working on a project that uses Node.js. I'm familiar with JavaScript, but not great. As part of that, I've run into a challenge that I'm not sure how to overcome.

I need to share some code on the server (Node.js) and my client-side (browser) app. I want to be able to access this code by typing the following:

myCompany.myProject.myFunction(someValue);

or just

myProject.myFunction(someValue);

In an attempt to do this, I have the following:

'use strict';

var myCompany = myCompany || {};
var myProject = myCompany.myProject || {};

myProject.myFunction= function(someValue) {
  console.log(someValue);
};

Inside of myFunction, I want to one thing if I'm running on the server (Node.js) and something different if I'm running in the browser. However, I'm not sure how to do that. I reviewed this post and this SO question, yet I still don't understand it.

Thank you for your help!

Community
  • 1
  • 1
xam developer
  • 1,923
  • 5
  • 27
  • 39

1 Answers1

0

You need something like this:

function someFunctionName() {

    // Common functional

    if (typeof module !== 'undefined' && module.exports) {
        // Do something only in Node.JS
    } else {
        // Do something else in the browser
    }

    // Common functional
}
micnic
  • 10,915
  • 5
  • 44
  • 55