0

I want variable identify once so;

├── project_folder

| ├── app.js //main file

| └── router/index.js

app.js

const express = require('express');
const app = express();
const path = require('path');
const router = require('./router/index');
const mysql = require('mysql');

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use('/',router);

app.listen( 8000, function(){
    console.log( 'Server listening on * 8000' );
});

index.js

//other codes
const connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : 'root',
    database : 'wordpress'
});

connection.connect(function(err){
    if(err)
        console.log(err);   
});
//other codes

error : mysql is not defined

I don't want identify mysql and other variables again.

How can I solve?

Thank you for your helping.

SOLVED

Create a settings.js Define settings in file

EXAMPLE

const testSettings = "test Settings...";

module.exports = {
    test:testSettings
}

In a file you want require('./settings');

Using: settings.test

3 Answers3

0

You need to import the modules that are required:

index.js

const mysql = require('mysql');

const connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : 'root',
    database : 'wordpress'
});

connection.connect(function(err) {
    if (err) {
        console.log(err); 
    }  
});
Miguel Mota
  • 20,135
  • 5
  • 45
  • 64
0

You just need to require('mysql') in you index.js file.
And in your app.js file, as you have already imported this file(index.js), this will lead to the execution of this file as soon as it is required by you in app.js file.

Therefore, you need not require('mysql') in the app.js file as this is the way NODE intends to work (modularizes the code).

it must be required in each file where you us mysql

const mysql = require('mysql');

    const connection =

 mysql.createConnection({
        host     : 'localhost',
        user     : 'root',
        password : 'root',
        database : 'wordpress'
    });

    connection.connect(function(err) {
        if (err) {
            console.log(err); 
        }  
    });

If you create any functions inside this index.js file which are required in other modules, you can module.exports them.

Edit:

Refer to this link for in-depth explanation on modules: https://nodejs.org/api/modules.html

Sunny
  • 544
  • 9
  • 20
0

As others answers pointed, you should import module using 'require()' when you want to access it in the file.

If you are asking how to initialize db connection without initializing it in every file, you can create module for db connection.

Check Dave's answer on this topic how does createConnection work with nodeJS in mysql?

Michal Biros
  • 410
  • 1
  • 5
  • 15