Search code examples
javascriptnode.jsmocha.jsnode-mysql

Why the variable is not visible from the imported file?


There are a code in main.js:

var test_mysql = require('./test_mysql.js')
... //some code
    before(function(){
        test_mysql.preparingDB(test_mysql.SQL_query.clear_data); // or test_mysql.preparingDB(SQL_query.clear_data); 
    });

A code in test_mysql.js:

var SQL_query = require('./SQL_query.js');
...//some code
exports.preparingDB = function(query){
    connection.connect(function(err){
        if (err){
            console.error('Error connecting: ' + err.stack);
            return;
        }
        console.log('Connected as id ' + connection.threadId);
    });
    console.log(query);  
    connection.query(query, function(err){
        if (err){       
            console.error('Error: ' + err.stack);
            throw err; /*не уверена, что оба сработают*/
        }
        console.log('Database preparation completed');
    });

A code in SQL_query.js:

exports.clear_data = 'SET FOREIGN_KEY_CHECKS=0;  -- \
TRUNCATE TABLE `billing_payment_gateway`;  -- \
TRUNCATE TABLE `fos_user`;  -- \
TRUNCATE TABLE `billing_account_has_product`;  -- \
TRUNCATE TABLE `billing_account`;  -- \
TRUNCATE TABLE `billing_product`; -- \
SET FOREIGN_KEY_CHECKS=1;'

When I try to run main.js, I'm recieve Error. In first case is TypeError: Cannot read property 'clear_data' of undefined. In another case is ReferenceError: SQL_query is not defined.

Why? What issue?

P.S. Ok. Explain to me please. someone. In test_mysql.js also require var mysql = require('mysql'); Why this module is visible in main.js????


Solution

  • In your test_mysql.js you export only preparingDB, so therefore this is the only thing from this module that's available from outside.

    You should also export SQL_query variable if you want it available from requiring modules