Developing an export feature for a mean application

Attempting to develop a basic module for organizing accounts on a website seemed like a straightforward task. I thought it would be as simple as creating a file with some functions, wrapping it in module.exports, and everything would work smoothly. However, it turned out that the reality was quite different - Bob is definitely not my uncle.

I created the following file:

module.exports = function(lameAccount) {
    lameAccount.initAccount( function ( myId, myName, done) {
        console.log("Will create" + myId);
        console.log("Name is " + myName);
        done(null,false,"This is just a hello");

    })
}

In the section where it is needed (the api router)

var lameAccountant                    = require('../modules/lameaccount.js')

And then call our function

lameAccount.initAccount(blockRecord._id, blockRecord.betName)

However, when attempting to utilize this functionality, an error occurs:

/Users/bengtbjorkberg/WebstormProjects/Challange/node_modules/mongoose/node_modules/mpromise/lib/promise.js:108
  if (this.ended && !this.hasRejectListeners()) throw reason;
                                                      ^
TypeError: undefined is not a function
    at EventEmitter.<anonymous> (/Users/bengtbjorkberg/WebstormProjects/Challange/routes/api.js:119:22)
    ... (error details continue)

============== Edit in regards to first answer ============

If this is indeed an anonymous function (which I believe it is), why does it function as intended in the following code snippets:

// expose this function to our app using module.exports
module.exports = function(passport) {

    // Passport session setup 
    passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, user);
        });
    });

and also within the API implementations:

module.exports = function(app, passport) {

    var urlencodedParser = bodyParser.urlencoded({ extended: false })
    
    app.use(bodyParser.json())

    // Route to retrieve list of users
    app.get('/api/userList', function(req, res){
       User.find({}, {'_id':1, 'userName':1},function(err, users) {
           if (err)
            res.send(err)

           res.json(users);
       })
    });

Does app.use allow for the inclusion of anonymous functions?

Answer №1

element, the code snippet provides instructions on how to properly handle an anonymous function attached to module.exports in JavaScript. By utilizing the anonymous function correctly or exposing the desired function, initAccount, developers can ensure that their code functions as intended. This approach allows for better organization and clarity when working with modules in different files.

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

Halting the node server that is currently listening on a designated port

Can I terminate an Express server listening on a specific port from a separate script on the same machine? Without using the original script. For example, if I start the server in one terminal window by running node directly or through a Grunt/Gulp task. ...

Problem with Azure Table JavaScript Solution

When attempting to utilize JavaScript to access Azure Storage Tables, I encountered an error that reads: "Error getting status from the table: TypeError: tableServiceClient.getTableClient is not a function." Despite finding multiple successful examples onl ...

Authentication in Express JS routing is implemented using a customized approach to

I recently developed a node js app using the express framework. One of the features I implemented is a middleware for restricting access to certain routes. Although the middleware is functioning properly, I am facing challenges in displaying data. For e ...

Unable to save text to file in both Javascript and PHP

I'm facing an issue with my website signup form. It consists of fields for email and password. The HTML triggers a JavaScript function which, in turn, calls PHP code to save the email to a file on the server. While the JavaScript seems to be functioni ...

Blue Jay Guarantees: Construct props object on the fly and execute simultaneously

If we take a look at this example: https://github.com/petkaantonov/bluebird/blob/master/API.md#props---promise Promise.props({ pictures: getPictures(), comments: getComments(), tweets: getTweets() }).then(function(result) { console.log(re ...

Angular 4/5 | Custom Dropdown Component

I have been working on a custom dropdown directive in Angular that I can attach to any DOM element. Below is the code for my directive: import { Directive, HostListener } from '@angular/core'; @Directive({ selector: '[appDropdown]' ...

The TransferList component in Material UI does not update its state based on props when using the useState

My TransferList component in Material UI receives an array of previously selected items as props.selectedItems. The props.Items contains all available items. I expected to see props.selectedItems in the left panel of TransferList, but the left panel is em ...

Is there a way to verify the phone number input field on my registration form along with the country code using geolocation

I'm currently working on a registration form that includes an input field for telephone number. I'd like to implement a feature where, upon filling out the form, the telephone input field automatically displays the country code by default. Would ...

Leveraging the Recyclability Aspect of a ReactJS Modal

Looking for a way to make a modal dynamic without duplicating too much code. Any suggestions on how to achieve this? I've managed to separate the state from the layout using render props. interface State { open: boolean; } interface InjectedMod ...

Using Node.js with sqlite3 for seamless data synchronization

Recently, I've been experimenting with developing a basic app using nodejs, socket.io, and sqlite as the database system. This project is primarily for learning purposes to gain a better understanding of how nodejs functions and to determine its suita ...

What is the best way to convert an ajax get request into a post request using jQuery?

I'm interested in transforming a GET request to a POST request: $.ajax({ url: '/items?ids=' + value.join(','), method: 'get', dataType: 'json' }) What changes do I need to make to turn this into a ...

Using AJAX and React to handle RESTful requests

Hello there, I am attempting to utilize a web service in React but am encountering issues with the AJAX function. I'm unsure if my code is working as expected. Here is a snippet of my code: prox= {"email":email, "password": password}; //tag comment $ ...

Problem with <meta> tag occurring when initial-scale is adjusted

Initially, in the index.html file: <meta name="viewport" content="width=device-width, initial-scale=1" /> I decided to modify it to: <meta name="viewport" content="width=device-width, initial-scale=2" /> ...

I encountered a PrimeVue error while running a Vue Jest test

When working on a Vue jest test, I encountered an error message "No PrimeVue Confirmation provided!" which seemed to be related to the useToast() and useConfirm() services. "transformIgnorePatterns": [ "<rootDir>/node_modules/(?! ...

Collaborating with Ladda button functionality

I have a button with ladda functionality, shown below. <button class="btn btn-primary btn-xs ladda-button" data-style="slide-left" data-size="xs" v-on:click="refreshPage()">Refresh</button> The onClick event is triggered by VueJs. When the b ...

Two select boxes trigger multiple sorting operations

Struggling to implement 2 different sorting operations on two separate columns in a datagrid, using 2 different select boxes has proven to be challenging. I attempted the code below, but as a beginner, I was unable to solve it... In HTML: <select ng ...

Is it possible to implement websockets with inversify-express-utils?

We are attempting to integrate websockets into our typescript application built on inversify-express-utils, but so far we have had no success: import 'reflect-metadata'; import {interfaces, InversifyExpressServer, TYPE} from 'inversify-expr ...

Finding the correlation between SVG element IDs and JSON keysUnderstanding how to pair up

Currently, I have an SVG file that can be viewed here. My goal is to present specific data when elements within the SVG are clicked. The data is in JSON format and I am looking to match each ID of an SVG element with a key in the JSON data. If both the key ...

Why am I encountering difficulties connecting to the Socket IO object in Node.js using Express?

Encountering a strange issue on the remote server side where everything works fine locally with a self-signed cert over https. However, when moving the code to the server, it works locally but not remotely. A node app is created and hosted on the server u ...

Is there a way for me to determine if an image created with Image() has had its source modified?

Is there a way to track changes in the src attribute of images created using the Image constructor on a webpage without needing the image to be fully loaded? I have attempted to override the Image.onload method, but it does not log anything: Image.prototy ...