


An introduction to two methods for solving circular dependency problems in Node.js
The content of this article is an introduction to two methods of solving circular dependency problems in Node.js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
The focus of this article is to explain how to solve the problem of circular dependencies. If you are interested in how this problem arises, you can Google it yourself.
How to reproduce this problem
// a.js const {sayB} = require('./b.js') sayB() function sayA () { console.log('say A') } module.exports = { sayA }
// b.js const {sayA} = require('./a.js') sayA() function sayB () { console.log('say B') } module.exports = { sayB }
Execute the following code
➜ test git:(master) ✗ node a.js /Users/dd/wj-gitlab/tools/test/b.js:3 sayA() ^ TypeError: sayA is not a function at Object.<anonymous> (/Users/dd/wj-gitlab/tools/test/b.js:3:1) at Module._compile (module.js:635:30) at Object.Module._extensions..js (module.js:646:10) at Module.load (module.js:554:32) at tryModuleLoad (module.js:497:12) at Function.Module._load (module.js:489:3) at Module.require (module.js:579:17) at require (internal/module.js:11:18) at Object.<anonymous> (/Users/dd/wj-gitlab/tools/test/a.js:1:78) at Module._compile (module.js:635:30)</anonymous></anonymous>
sayA is not a function
So what is sayA? In fact, it is undefined
When you encounter this kind of problem, you'd better realize that it may be a circular dependency problem
, otherwise finding the problem may be half the result.
How to find files with circular dependencies
The sample code above is very simple, with 2 files, it is easy to find circular dependencies. If there are more than a dozen files, it is very troublesome to manually find the circularly dependent files.
The following is a tool madge is recommended, which can visually view the dependencies between files.
Pay attention to Figure 1 below. Taking cli.js as the starting point, all arrows expand to the right, which shows that there are no circular dependencies. If there is an arrow pointing countercurrent to the left, it may be a point of circular dependence.
In Figure 2, the left arrow appears, indicating that there is a circular dependency, indicating that the cycle needs to be broken here.
【Picture 1】
##【Picture 2】
How to solve circular dependencies
Option 1: Export your own module firstPut module.exports at the head of the file, export your own module first, and then Import other modules// a.js module.exports = { sayA } const {sayB} = require('./b.js') sayB() function sayA () { console.log('say A') }
// b.js module.exports = { sayB } const {sayA} = require('./a.js') console.log(typeof sayA) sayA() function sayB () { console.log('say A') }
Option 2: Indirect call
By introducing an event message passing, multiple modules can pass messages indirectly, between multiple modules You can also call each other by sending messages.// a.js require('./b.js') const bus = require('./bus.js') bus.on('sayA', sayA) setTimeout(() => { bus.emit('sayB') }, 0) function sayA () { console.log('say A') } module.exports = { sayA }
// b.js const bus = require('./bus.js') bus.on('sayB', sayB) setTimeout(() => { bus.emit('sayA') }, 0) function sayB () { console.log('say B') } module.exports = { sayB }
// bus.js const EventEmitter = require('events') class MyEmitter extends EventEmitter {} module.exports = new MyEmitter()
Summary
When circular dependencies occur, there is often a problem with the structure of the code. You should take the initiative to avoid problems such as circular dependencies, but when you encounter such problems and cannot avoid them, you should also realize that the problems are caused by circular dependencies and find solutions. Finally, an interesting question is given. What will the following code output when running node a.js? Why is this happening?// a.js var moduleB = require('./b.js') setInterval(() => { console.log('setInterval A') }, 500) setTimeout(() => { console.log('setTimeout moduleA') moduleB.sayB() }, 2000) function sayA () { console.log('say A') } module.exports = { sayA }rrree
The above is the detailed content of An introduction to two methods for solving circular dependency problems in Node.js. For more information, please follow other related articles on the PHP Chinese website!

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version
Visual web development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.