Guide on exporting and implementing a function with Express

I'm facing a challenge with two files - alarm.js and notifications.js. In alarm.js, I need to invoke a method named sendPush from notifications.js.

My attempted solution:
I tried exporting the function from notifications.js:

module.exports.sendPush = function(params){
   console.log("sendPush from notifcations.js called");
   console.log(params);
}

Then, I imported it in alarm.js and attempted to use it :

let helperNotif = require('./notifications')
router.post("/", async (req, res) => {
    const params = {
        param1: 'a',
        param2: 'b'
    }
    helperNotif.sendPush(params)    
});

The issue at hand:
Despite my efforts, I keep encountering an error stating that

helperNotif.sendPush is not a function

The main concern:
How can I successfully call the notification.js sendPush function from my alarm.js file?

[EDIT] It's worth mentioning that in notifications.js, there are some router.get and router.post functions followed by module.exports = router; at the end.

Answer №1

If the content of your notifications.js file ends with module.exports = router, it will replace any previous definition of module.exports.sendPush = .... In order to export both the router and sendPush, you can do the following:

function sendPush(params){
   console.log("sendPush from notifications.js has been invoked");
   console.log(params);
}
...
module.exports = {router, sendPush};

To import the router in another file, you will need to write:

const {router} = require("./notifications.js");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The functionality of keydown is not functioning properly in the Chrome browser

Hey there, I've been working on some scripts and testing them in Firefox where they're running smoothly. However, when I tried testing them in Chrome, the keydown event doesn't seem to be working. I also attempted the keyup event with no suc ...

Change the class name using jQuery when scrolling

Currently utilizing bootstrap as my primary css framework. My goal is to dynamically toggle a class on the navbar once the user scrolls past the prominent header image located at the top of the website. UPDATE: Admitting I made an error and had a momenta ...

Middleware caching for faster responses

I have been working on incorporating caching into my project using express middleware, and it seems to be functioning well. However, I've encountered an issue with an endless loop. Within my router, I have the following route: router.get('/test ...

Fetching form data using the .add method in PHP

I'm facing an issue where I upload a text/plain file and use jQuery AJAX to pass it to PHP for processing. However, the jQuery AJAX call is returning an error: jquery-2.2.3.js:8998 Uncaught TypeError: Illegal invocation https://i.sstatic.net/eFjYF.png ...

The function insertAdjacentHTML does not seem to be functioning properly when used with a

I am working with a parent element that contains some child elements. I create a DocumentFragment and clone certain nodes, adding them to the fragment. Then, I attempt to insert the fragment into the DOM using the insertAdjacentHTML method. Here is an ex ...

When the checkbox is ticked, icheck will make a POST request, but it won't

I am currently experimenting with using icheck to handle POST requests for a temporary table. My goal is to add an entry when a box is checked and remove it when unchecked. Currently, when I check the box, it alerts me and successfully stores the informati ...

Encountering an issue while trying to read a text file using JavaScript

As I embark on my journey to understand how to read a text file locally using JavaScript and Ajax, I find myself lost in the sea of online tutorials. Despite diligently following these resources, I am unable to successfully display the contents of the .txt ...

Preventing form reload on route change in PHP

I've set up a basic form on my index.php page: <div class="form-container"> <form id="create-form" action="create.php" method="POST"> <label for="name">Name:</label> ...

Update the sum upon deleting a feature in an HTML and JavaScript form

Once a row or field is added, this function will display a delete link. When clicked, it will remove the row or field: var ct = 1; function addNewRow(){ ct++; var divElement = document.createElement('div'); divElement.id = ct; // Code to cr ...

jquery mobile listview extension not functioning as expected

My JQM menu is displayed as a listview, and I want it to be normal on every page except one where it should have 2 extra items. Despite searching online for solutions, nothing seems to work. Here are some of the things I've attempted: -location.reloa ...

Restrict the vertical camera rotation

Utilizing JSModeler for showcasing OBJ files. The software integrates THREE.JS and generates a PerspectiveCamera. My goal is to restrict the camera's Y-axis movement to prevent it from going beneath the object. While I am familiar with achieving this ...

Arrays in Memory Games

Hello everyone, I'm currently in the process of creating a simple memory game but I've encountered some challenges along the way. Initially, I set up the basic structure and decided to enhance it by adding different difficulty levels. To achieve ...

org.openqa.selenium.UnexpectedAlertOpenException: error occurred due to an unanticipated alert opening

While using the Chrome Driver to test a webpage, I typically have no issues. However, there are times when exceptions occur: org.openqa.selenium.UnhandledAlertException: unexpected alert open (Session info: chrome=38.0.2125.111) (Driver info: chromedri ...

Select menu with personalized choices

I am in need of a specific feature for my website. Currently, I have implemented a basic select element but I want to add the option for users to input a range as the last item. Here is an example of what I'm trying to achieve: <select> <op ...

I am not forcing the Angular module to conform to my perspective

Hello, I am new to Angular and trying to experiment with some code. However, I seem to be stuck with the app.js file which is throwing an error: Uncaught SyntaxError: Unexpected token . Below is the structure of my application, which I obtained by cloning ...

A guide to dynamically adjusting CSS with JavaScript

Currently, I am working on a complex animation project where I am experimenting with incorporating effects by dynamically adding classes based on the value that I receive. I have various CSS classes at my disposal and I am seeking to understand how to eff ...

Using THREE.js to shoot a ball with a curve on the X or Z axis

As a beginner in THREE.js and lacking knowledge in physics, my goal is to create a top-view football manager game with realistic ball movement. I have successfully made the ball move and rotate in the right direction, adjusting its path when it reaches bou ...

a JavaScript method in Selenium for performing a double-click action on a WebElement

Since selenium allows for the execution of JavaScript, I am interested in clicking and double-clicking on a web element or x, y coordinate using JavaScript. I prefer to use JavaScript because the web element in question is a Flash/SVG object on the browser ...

Receiving alerts about props passed in MUI styled components triggering React's lack of recognition

I have a unique component design that requires dynamic props to determine its styling. Here is an example: const StyledTypography = styled(Typography)( ({ myColor = "black", isLarge = false }) => ({ "&&": { fontSi ...

Is it acceptable for a video to autoplay even if it is not connected to the DOM?

Consider the following three scenarios: document.adoptNode, document.importNode, and document.createElement with assigned properties. In all cases, the video autoplay feature is activated even when it's not connected to the DOM. This behavior diffe ...