What could be causing the double execution of a Requirejs call in Node without any apparent reason

I'm currently trying to understand how to use requirejs in node. According to the RequireJS in Node manual, I should be able to run a synchronous call by using the following code snippet:

//Retrieves the module value for 'a' synchronously
var a = requirejs('a') )

However, when I attempted this approach, it seemed like the request was executed twice?

In my part0_start.js file, I have the following code:

var requirejs = require('requirejs');
requirejs.config({
    nodeRequire : require 
});
var part1_setup = requirejs( 'part1_setup' ) 
console.log( 'part1_setup complete')

In my part1_setup.js file, I have the following code:

requirejs([], function() {
    console.log( 'setup');
})

Based on this setup, I expect the output to be:

setup
part1_setup complete

But instead, the actual output is:

setup
setup
part1_setup complete

Could someone provide some insight into what might be happening here? I would greatly appreciate it.

Answer №1

It is necessary to substitute the requirejs invocation in your part1_setup.js with define.

In the case of using RequireJS in node, there is a peculiarity: if RequireJS fails to load a module by itself, it will attempt to utilize Node's require to load the module. Here is what happens with your piece of code:

  1. The statement

    var part1_setup = requirejs( 'part1_setup' )
    instructs RequireJS to load the part1_setup1 module. Note that here you are employing a synchronous form of the require call (although its name is requirejs, it actually corresponds to RequireJS' own require call). In a browser environment, this kind of call is not truly synchronous (therefore, your specific call would fail); however, in Node, it is genuinely synchronous.

  2. RequireJS loads and executes your module. Due to the absence of an anonymous define within it (i.e., a define that does not specify a module name), the module loading operation fails. To allow RequireJS to identify which factory function should be executed for defining the module, you need to include an anonymous define. Nevertheless, the code within the file is indeed executed, meaning that you are informing RequireJS "when the dependencies [] have been loaded, then execute my callback". However, in this case, there are no dependencies to load. Therefore, RequireJS executes the callback that outputs setup.

  3. This behavior is specific to executing RequireJS in Node: Since the module loading process failed, RequireJS then invokes Node's require function using your module name as an argument. Node proceeds to locate and load the module. Consequently, Node re-executes the code within the file a second time, and once again, requirejs([],... is run. Thus, the callback that prints setup is executed for a second time.

In your module files, it is advisable to consistently include a define rather than a require (or requirejs) call.

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

Issue: Error code 0308010C encountered in the digital envelope routines, indicating unsupport for the command npm run storybook

Whenever I attempt to run npm run storybook An error pops up in the terminal: Error: error:0308010C:digital envelope routines::unsupported at new Hash (node:internal/crypto/hash:71:19) at Object.createHash (node:crypto:133:10) Operating System - ...

Error: internalBinding function is not recognized

Encountering a problem in ASP.NET Zero 5.x where npm run create-bundles fails to execute. Currently working on an existing licensed project using the ASP.NET Zero's ASP.NET Core MVC + jQuery base solution, built on the ASP.NET Boilerplate framework. ...

Why is my Node.js express application throwing a 404 POST error?

I am facing an issue while trying to build a node.js application with express. Whenever I attempt to log in and my index.ejs file sends a post request to the server, I encounter a 404 error. Being new to programming, I am seeking assistance from someone wh ...

Following the successful installation of create-react-app, Npm start is refusing to function properly. The error message Enoent with the error number -4058 is

I'm having trouble running my create-react-app on VS code - the npm start command is giving me an error message. Can someone please assist? $ npm start npm ERR! path C:\Users\Jay\Desktop\NucampFolder\3-React\package.json ...

Encountered a Gulp error: unable to spawn process due to E

gulpfile.js 'use strict'; var gulp = require('gulp'); gulp.paths = { src: 'src', dist: 'dist', tmp: '.tmp', e2e: 'e2e' }; require('require-dir')('./gulp'); gulp.ta ...

"Encountering an issue while installing Express with the Node Package Manager

While trying to install express using the node package manager on my Windows 7 x64 machine, I encountered the following error. I am running cmd as an administrator. Can anyone provide assistance? Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Mic ...

Guide to uploading files from various fields within a single MongoDB collection using Multer

I need help with uploading images from multiple fields in the same collection. Currently, I can only upload using one field. route : service.js router.post('/register', upload.array('daycare.DCImage',10),(req, res) => { var paths ...

Breaking down objects and setting default values

In need of assistance with resolving an issue related to default parameters and object destructuring. The 'product' object that I am working with has the following structure: { name: "Slip Dress", priceInCents: 8800, availableSizes ...

The Node.js server continues to stream data even after the client has disconnected

I recently set up a small Node.js + express server with a dummy download method in place: app.get("/download",function(req,res) { res.set('Content-Type', 'application/octet-stream'); res.set('Content-Length', 1000000 ...

Puppeteer: Navigate to a specific page number

I'm encountering an issue with a table and page numbers as links, such as: 1, 2, 3, 4 etc… -> each number is a link. Attempted to create a loop to click on different page numbers. On the first iteration, I can reach page 2. However, on the secon ...

Transfer a downloaded file from a secured pathway to the web browser

I have a setup with a react frontend and a nodejs/express backend. The backend has a protected route for serving files (downloads) like so: GET /api/file/:id When the frontend initiates a file download, it makes a request to this endpoint using the follo ...

Error 502 is being returned by the Nginx server for specific directories within the Express Application

Currently, I have an express application running on Ubuntu with nginx as the web server. Everything was functioning correctly until today when I attempted to add two new directories using the app.get method and re-deployed my app. Unfortunately, the new ...

Angular does not receive events from Socket.io

Recently I started coding with AngularJS and decided to build a real-time app using Socket.io: The service I'm using shows that the connection is fine on the console. Here's a picture of the Console.log output However, when I attempt to emit c ...

Instructions for utilizing executables from a package that has been installed locally in the node_modules directory

Is there a way to utilize a local version of a module in node.js? For instance, after installing coffee-script in my app: npm install coffee-script By default, this installation places coffee-script in ./node_modules, with the coffee command located at . ...

Extracting a Single Component from a Dynamic Zone in the Strapi Bookshelf: A Quick Guide

Currently, I have a dynamiczone field in my model that I require for certain endpoints. In order to control the population of this field, I set "autoPopulate": false. However, I am facing an issue where I need to retrieve only one specific component, such ...

Changes in the volume of a Docker node running Express are not being updated in the container

Recently, I set up an express app on my host and linked it with a running container using a volume: docker run -d -p 80:8080 -v $(pwd):/www -w "/www" node However, I noticed that when I make changes to the code on my host and refresh the web page, the up ...

Execute npm and node using ansible

I am facing a challenge with the script execution on a machine that has zsh installed. Here is what I have set up: Software Installed # Install NVM sudo curl https://raw.githubusercontent.com/creationix/nvm/v0.31.0/install.sh | bash ## Reload shell to st ...

Accessing the Current User Using Firebase Admin SDK in Node.js

Is there a way to retrieve the currentUser in firebase admin SDK? While in client SDK we have options like onAuthStateChanged() or firebase.auth().currentUser() When using NodeJs Server.js with firebase admin SDK, the onAuthStateChanged() method doesn&a ...

Issues have been arising with node.js causing interference with other programs on my Mac

Recently delving into the world of Node and JavaScript, I've encountered a situation where my program, which involves heavy network API calls and result processing, is causing other programs on my Mac (such as Outlook and Chrome) to become unresponsiv ...

Two applications installed on a single server, each running on its own port. The first application is unable to communicate with the second

I have two applications running on the same VPS (Ubuntu) and domain. The first is a Node.js app running on port 80, while the second is a Python (Flask) app running under Apache on port 3000. The Python app has a simple API with one endpoint /test. When I ...