Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...