Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

javascript - Node.js: how to resolve a circular dependency

I know this question has been asked multiple times, but my case is specific:

I have three files, a controller.js, router.js and an app.js,

router.js imports controller.js, app.js imports router.js

I need to import something from app.js to controller.js, how would I do that?

question from:https://stackoverflow.com/questions/65835944/node-js-how-to-resolve-a-circular-dependency

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you're probably better off restructuring your code to not need it. Maybe create a third class that uses the other two to accomplish what you need, if you have to use a function in app.js you can do like this:

before requiring you should exports express() and functions

app.js

const express = require("express");
const func = () => {
  console.log("I'm in App");
};
var exportFiles = module.exports = {
  app: express(),
  func: func,
};
var { app } = exportFiles;
const fs = require("fs");
const path = require("path");
const bodyParser = require("body-parser");

app.listen(8080, () => {
  console.log("server port is 8080")
})

contolers.js

const {func} = require('../app');

when you call func() in controller result is :

func() // I'm in App

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...