Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can't I connect to SQLServer uisng NodeJS?

I’m new using Node JS and now I’m creating a project that connects to SQL Server, but when I use the command node Database\connect.js It simply does do nothing, as it should do a console.log that it did connect or it didn’t.

Here is my package.json

{
  "dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "tedious": "^14.0.0"
  },
  "name": "weather-nodejs-apirest",
  "version": "1.0.0",
  "main": "connect.js",
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": ""
}

And here is my connect.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var Connection = require('tedious').Connection;
var config = {
    server: 'SERVERNAME',
    authentication: {
        type: 'default',
        options: {
            userName: 'sa',
            password: 'password'
        }
    },
    options: {
        database: 'weather_app',
        // instanceName: 'Sqlexpress',
        rowCollectionOnDone: true,
        useColumnNames: false
    }
}

var connection = new Connection(config);
connection.on('connect', function (err) {
    if (err) {
        console.log(err);
    } else {
        console.log('Connected');
    }
});

module.exports = connection;

>Solution :

The connection.on(...) method will not initiate the database connection itself. It only runs when the application initiates it using connection.connect() method.

Since you are exporting connection to the outside from connect.js, You should import and initiate the connection somewhere (mostly in application entry point),

const connection = require('path/to/connect.js');

// initiate
connection.connect();

Doc: http://tediousjs.github.io/tedious/getting-started.html

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading