NodeJS如何实现类似PHP的文件引入?数据库连接抽离报错求解
import Function Error When Separating Connection Logic Hey there, I totally get where you're coming from—switching from PHP's straightforward include to Node.js's module system can feel a bit confusing at first, especially when you're used to reusing everything directly. Let's break down what went wrong and fix that import function error.
The Problem with Your Approach
When you exported a function that returns the connection, calling require('./config.js') gave you the function itself, not the Sequelize connection instance. That's why trying to call connection.import() threw an error—functions don't have an import method attached to them!
The Correct Solution: Export the Sequelize Instance Directly
Instead of wrapping your connection in a function, create the Sequelize instance in your config file and export it directly. Here's how:
Step 1: Update Your config.js File
// config.js const { Sequelize } = require('sequelize'); // Create your Sequelize connection instance const dbConnection = new Sequelize( 'your_database_name', 'your_username', 'your_password', { host: 'localhost', dialect: 'mysql' // Replace with your database dialect (postgres, sqlite, etc.) } ); // Export the instance directly, not a function module.exports = dbConnection;
Step 2: Import and Use the Connection in Your Main File
Now when you require the config file, you'll get the actual Sequelize instance, which has the import method you need:
// Main file (e.g., app.js or index.js) const connection = require('./config.js'); // Now this will work perfectly const Users = connection.import(__dirname + "/models/users.js");
What If You Need Dynamic Initialization?
If you ever need to pass dynamic values (like environment variables) to your connection, you can still use a function—but you'll need to execute it to get the instance:
Updated config.js for Dynamic Setup
// config.js const { Sequelize } = require('sequelize'); module.exports = (dbName, dbUser, dbPass) => { return new Sequelize(dbName, dbUser, dbPass, { host: 'localhost', dialect: 'mysql' }); };
Using It in Your Main File
const getDbConnection = require('./config.js'); // Execute the function to get the instance const connection = getDbConnection('your_db', 'user', 'pass'); const Users = connection.import(__dirname + "/models/users.js");
That's all there is to it! The key difference from PHP's include is that Node.js modules export values (instances, functions, objects, etc.) rather than just dumping code into the current scope—so you just need to make sure you're exporting the right value.
内容的提问来源于stack exchange,提问作者Joseph Astrahan

