Home > other >  how to get a file without requiring in node.js?
how to get a file without requiring in node.js?

Time:09-23

I have tons of files where I have to add this function.

const Media  = require("../../functions/Media");
Media(....);

Is there any way to:

Directly add Media() function without requiring the file

CodePudding user response:

Try declaring it as global in index file:

const {Media} = require('./functions/Media');

global.MediaGlobal = function Media(input) {
   Media(input)
}

CodePudding user response:

It really depends on the framework you are using. You need to find the starting index file and append all global functions there. Samples are given below.

// Override Globals in Backend Nodejs

if (typeof global !== "undefined") {
  global.someGlobalFunction = function () {};
}
// Override Globals in Frontend Nodejs/reactjs
// Override Globals in Frontend javascript written on nodejs

if (typeof window !== "undefined") {
  window.someGlobalFunction = function () {};
}

Node.js Express (Backend)

Look for file define server, app.listen, Defined on top before import other modules

Node.js React (Frontend)

Look for file define react.render, app.jsx, Defined on top before import other modules

Learn the concept of polyfill:

Best way to polyfill ES6 features in React app that uses create-react-app

  • Related