Connection to oracle database via nodeJS - node.js

I'm trying to establish an Oracle connection using NodeJS but while trying to connect i am receiving below error.
Error: Error: DPI-1047: Cannot locate a 64-bit Oracle Client library: "The specified module could not be found". See https://oracle.github.io/odpi/doc/installation.html#windows for help
Node-oracledb installation instructions: https://oracle.github.io/node-oracledb/INSTALL.html
You must have 64-bit Oracle client libraries in your PATH environment variable.
If you do not have Oracle Database on this computer, then install the Instant Client Basic or Basic Light package from
http://www.oracle.com/technetwork/topics/winx64soft-089540.html
A Microsoft Visual Studio Redistributable suitable for your Oracle client library version must be available.
at OracleDb.getConnection (C:\NodeCon\node_modules\oracledb\lib\oracledb.js:270:10)
at C:\NodeCon\node_modules\oracledb\lib\util.js:180:16
at new Promise (<anonymous>)
at OracleDb.getConnection (C:\NodeCon\node_modules\oracledb\lib\util.js:168:14)
at C:\NodeCon\server.js:41:32
at Object.<anonymous> (C:\NodeCon\server.js:58:3)
at Module._compile (internal/modules/cjs/loader.js:956:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
at Module.load (internal/modules/cjs/loader.js:812:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14) {
errorNum: 0,
offset: 0
I've downloaded and installed 64 bit Oracle Client Library but still below error appears.
Using Visual Studio Code v.1.36 as my editor.
NodeJS code i'm using is as below :
let connection;
var oracledb = require('oracledb');
(async function(){
try{
connection = await oracledb.getConnection({
user: 'Username',
password: 'Password',
connectString: 'hostname:portname/servicename'
});
console.log("Successfully connected");
} catch(err){
console.log("NOT connected");
}finally{
if(connection){
try{
await connection.close();
}catch(err){
console.log("Errror");
}
}
}
})()
Any help will be much appreciated. Thanks.

This got resolved by following code:
oracledb.getConnection({
user: 'username',
password: 'Password',
connectString: 'hostname:portname/servicename'
},
function(err, connection) {
if (err) throw err;
connection.execute(
//Your database query here.
//below code if you want to fetch data from database and show it on terminal
function(err,results){
var metaData = {};
var rows = {};
console.log("error")
if (err){
throw err
}
metaData.name1 = results.metaData[0].name;
metaData.name2 = results.metaData[1].name;
rows.row1 = results.rows[0][0];
rows.row2 = results.rows[0][1];
rows.row3 = results.rows[0][2];
console.log(metaData.name1+" : "+rows.row1)
console.log(metaData.name2+" : "+rows.row2)
console.log("Successfully connected");
);
}
And if you're connecting via VPN make sure to connect to the server first then run above.

Related

How to solve this Error: Cannot find module 'ibm-watson'

I have installed ibm-watson using "npm install ibm-watson" command
I can see the folder and its file in the node_modules folder, but still showing this error.
Node version - v10.15.3
const watson = require('ibm-watson');
const { IamAuthenticator } = require('ibm-watson/auth');
const { BasicAuthenticator } = require('ibm-watson/auth');
// to get an IAM Access Token
const authorization = new watson.AuthorizationV1({
authenticator: new IamAuthenticator({ apikey: 'fakekey-1234' }),
});
authorization.getToken(function (err, token) {
if (!token) {
console.log('error: ', err);
} else {
// Use your token here
}
});
Other modules are importing fine, Only this module not importing.
internal/modules/cjs/loader.js:584
throw err;
^
Error: Cannot find module 'ibm-watson'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
at Function.Module._load (internal/modules/cjs/loader.js:508:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object.<anonymous>
I've just faced this issue. I did not install the correct version of the package. Please check the apidocs for Node to see the correct version of IBM Watson npm package that you need. for me I needed 5.6.0.
You can install it with the following command:
npm install ibm-watson#^5.6.0
As you are getting a token, I am going to guess that you are using Speech To Text. As the comments have suggested the failing line is const watson = require('ibm-watson'); because it isn't exported. Instead you would use, as per the API documentation - https://cloud.ibm.com/apidocs/speech-to-text/speech-to-text?code=node#authentication:
const SpeechToTextV1 = require('ibm-watson/speech-to-text/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
const { IamTokenManager } = require('ibm-watson/auth');
If it's not STT that you are using then the other services work the same way when requiring ibm-watson. Links to the API Docs can be found here - https://cloud.ibm.com/apidocs
I faced the same problem. 
After reading the code, I understood.
There is only sdk.ts file, not index.ts file.
https://github.com/watson-developer-cloud/node-sdk
// const watson = require('ibm-watson');
const watson = require('ibm-watson/sdk');
But I still got the error.
Eventually it worked if I wrote the following
import AuthorizationV1 from 'ibm-watson/authorization/v1'
import { IamAuthenticator } from 'ibm-watson/auth'
const apikey = '********'
const authorization = new AuthorizationV1({
url: 'https://iam.cloud.ibm.com/identity/token',
authenticator: new IamAuthenticator({ apikey }),
})
authorization.getToken(function (err, token) {
if (!token) {
console.log('error: ', err);
} else {
// Use your token here
}
});
But there is a CORS problem. I don't know any more.
The answer was written here. I need to do it on the server side
https://github.com/watson-developer-cloud/node-sdk/issues/884#issuecomment-515050023

Is it possible to connect to mssql with windows auth mode from a nodejs app running on linux?

I'm trying to connect to a mssql with Windows authentication mode (can't change that) from nodejs running on a linux machine.
I tried many things, all of them resulted in nearly the same error, here is an attempt using tedious with this simple code running on a linux machine with nodejs:
let tedious = require('tedious');
let Connection = tedious.Connection;
const config = {
userName: 'myUserName',
password: 'myPassword',
server: 'MyServ',
options: {
database: 'MyDbName'
}
}
function handleConnection(err: any) {
if (err) console.error("error connecting :-(", err);
else console.log("successfully connected!!")
}
let connection = new Connection(config);
connection.on('connect', handleConnection);
I get this error
error connecting :-( { ConnectionError: Login failed for user ''.
at ConnectionError (./node_modules/tedious/lib/errors.js:13:12)
at Parser.tokenStreamParser.on.token (./node_modules/tedious/lib/connection.js:848:51)
at Parser.emit (events.js:198:13)
at Parser.parser.on.token (./node_modules/tedious/lib/token/token-stream-parser.js:37:14)
at Parser.emit (events.js:198:13)
at addChunk (./node_modules/readable-stream/lib/_stream_readable.js:298:12)
at readableAddChunk (./node_modules/readable-stream/lib/_stream_readable.js:280:11)
at Parser.Readable.push (./node_modules/readable-stream/lib/_stream_readable.js:241:10)
at Parser.Transform.push (./node_modules/readable-stream/lib/_stream_transform.js:139:32)
at doneParsing (./node_modules/tedious/lib/token/stream-parser.js:122:14) message: 'Login failed for user \'\'.', code: 'ELOGIN' }
The credentials I used do have SQL rights (tested with ODBC on windows machine).
Am I doing something wrong or is it just impossible ?
#ADyson thank you a lot for your informations, you managed to pinpoint the solution to my poorly formulated problem caused by my total lack of knowledge on the subject, really thank you again. the solution was to use domain login this snippet worked :
const config = {
user: MyUserName,
password: MyPassword,
server: 'MyServAdress',
database: 'MyDbName,
domain: 'MyDomain'
}
const sql = require('mssql');
sql.connect(config).then((pool: any) => {
console.log('connected!');
}).catch((err: any) => {
console.log(err);
});
Yes indeed, it's possible to receive data form a linux client using windows authentication only enabled. MS SQL Server and NodeJS Linux Server are in the same network. The linux Server isn't domain-joined:
I used this to run execute my query:
const sql = require('mssql')
const config = {
server: 'SERVER',
database: 'DATABASE',
user: 'USER',
password: 'PASSWORD',
domain: 'DOMAIN',
options: {
enableArithAbort: true // required, otherwise deprecation warning
}
}
sql.connect(config)
.then((conn) => {
console.log('MSSQL: connected');
conn.query(`SELECT ..`)
.then(data => console.log(data))
.then(() => conn.close())
}).catch(err => { console.log(err) });

Connect Node.js BOT to MS Azure SQL database

I have a working MS Teams bot written in Node.js. The bot asks a series of questions and currently displays the responses at the end by accessing the session variables. All well and good.
Now I am attempting to store the session variables in a MS Azure SQL DB. The DB is correctly set up in Azure as I can access and write data to it in SSMS. But I believe I am probably connecting incorrectly to the DB in my bot code. The bot code I am using is pulled from:
connecting to SQL using Node.js
That code makes sense to me. But how do I use that code in my bot? Here is what I have attempted thus far...
Currently I am using the local memory MemoryBotStorage() and setting to that.
var inMemoryStorage = new builder.MemoryBotStorage();
.set('storage', inMemoryStorage)
In another Microsoft article dealing with the Azure Cosmos DB it states "4.Specify that you want to use your custom database instead of the in-memory storage." So from this I deduce that I hafta add my instantiated sql db to the .set('storage', DB Goes Here) but my attempts have failed and I am not sure if I am even correct?
So my question is how do I correctly access the Azure sql server DB form my bot code - and is the link I provided even the correct way?
Thank you
Note - This code sample worked for me - I was able to connect and query my Azure DB - but it is only DB code and does not take into consideration bot code.
EDIT - Code:
const builder = require('botbuilder');
const builderTeams = require('botbuilder-teams');
const restify = require('restify');
const connector = new builderTeams.TeamsChatConnector(
{
appId: "My app ID,
appPassword: "My App PW",
}
);
var inMemoryStorage = new builder.MemoryBotStorage();
const bot = new builder.UniversalBot(connector, [
function (session) {
session.send("Welcome.");
builder.Prompts.text(session, "Question1?");
},
function (session, results) {
session.dialogData.question1 = results.response;
builder.Prompts.text(session, "Question2?");
},
function (session, results) {
session.dialogData.Question2 = results.response;
builder.Prompts.text(session, "Question3?");
},
function (session, results) {
session.dialogData.Question3 = results.response;
// Begin DB
var Connection = require('tedious').Connection;
var config = {
userName: 'myusername',
password: 'mypw',
server: 'myserver.database.windows.net',
// If you are on Azure SQL Database, you need these next options.
options: { encrypt: true, database: 'mydb' }
};
var connection = new Connection(config);
connection.on('connect', function (err) {
// If no error, then good to proceed.
console.log("Connected");
executeStatement1();
});
var Request = require('tedious').Request
var TYPES = require('tedious').TYPES;
function executeStatement1() {
request = new Request("INSERT my (Username, Question1, Question2, Question3, StatusDate) VALUES (#Username, #Question1, #Question2, #Question3, CURRENT_TIMESTAMP);", function (err) {
if (err) {
console.log(err);
}
});
request.addParameter('Username', TYPES.NVarChar, session.userData.userName);
request.addParameter('Question1', TYPES.NVarChar, session.dialogData.Question1);
request.addParameter('Question2', TYPES.NVarChar, session.dialogData.Question2);
request.addParameter('Question3', TYPES.NVarChar, session.dialogData.Question3);
request.on('row', function (columns) {
columns.forEach(function (column) {
if (column.value === null) {
console.log('NULL');
} else {
console.log("ID of inserted item is " + column.value);
}
});
});
connection.execSql(request);
// End DB
// Process request and display details
session.endDialog();
}
]).set('storage', inMemoryStorage)
const server = restify.createServer();
server.post('api/messages', connector.listen());
server.listen(portnumber)
Error when running with npm start:
npm start
> simplebot#1.0.0 start C:\Developer\dailyStatus
> node index.js
C:\Developer\dailyStatus\index.js:81
]).set('storage', inMemoryStorage)
^
SyntaxError: Unexpected token ]
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:616:28)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! simplebot#1.0.0 start: `node index.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the simplebot#1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely...
npm ERR! A complete log of this run can be found in:
npm ERR! C: etc.
FINAL
I was able to able to get this working with this tutorial. Thanks also to Marc LeFleur.
You have several typos. For example, you're missing the closing " on appId:
const connector = new builderTeams.TeamsChatConnector(
{
appId: "My app ID",
appPassword: "My App PW",
}
);
You also can't declare the function executeStatement1() {...} function within the your IDialogWaterfallStep function. This needs to live outside the constructor and called from the IDialogWaterfallStep.

net.Stream is not a constructor - Node Postgres

I'm trying to connect a Node.js app with a PostgreSQL server. It seems that no matter what I use, I end up with the same error:
bundle.js:16177 ERROR: TypeError: net.Stream is not a constructor
at new Connection (bundle.js:10133)
at new Client (bundle.js:9704)
at Object.create (bundle.js:11308)
at Pool._createResource (bundle.js:510)
at Pool.dispense [as _dispense] (bundle.js:498)
at Pool.acquire (bundle.js:573)
at Pool.pool.connect (bundle.js:11359)
at PG.connect (bundle.js:10876)
at bundle.js:1642
At first I was declaring a new pg.Client() like the example in the documentation here, but got the above error discovered that might be a bad idea according to this stack overflow post.
I tried using pg.connect():
var pg = require('pg'); //postgresql dependency
var connectionString = "postgres://postgres:thisissuchagoodpassword#PostgreSQL/localhost:5432/Milestone1DB"
console.log("Initiating...");
//var connectionString = "postgres://postgres:thisissuchagoodpassword#PostgreSQL9.6/localhost:5432/Milestone1DB";
//var client = new pg.Client();
//connect to the database
console.log("Attempting to connect to the database");
pg.connect(function (err, client, done)
{
if(err)
{
console.log("Error connecting to the database.");
throw err;
}
client.query("SELECT DISTINCT state FROM business ORDER BY state", function (err, result)
{
if(err)
{
console.log("Query resulted in an error.");
throw err;
}
console.log(result.rows[0]);
client.end(function (err)
{
if(err)
{
console.log("Error disconnecting from the databse.");
throw err;
}
});
});
});
Here is the pg-promise code that I tried:
var pgp = require('pg-promise');
var cn = {
host: 'localhost', // server name or IP address;
port: 5432,
database: 'Milestone1DB',
user: 'postgres',
password: 'thisissuchagoodpassword'
};
var db = pgp(cn); // database instance;
db.any("select distict state from business order by state;")
.then(data => {
console.log("DATA:", data);
})
.catch(error => {
console.log("ERROR:", error);
});
I must be missing something, but I don't know where to look. Thank you to anyone who can help me figure out what this error means.
Make sure you are not crossing a context boundary that is corrupting the net prototype chain and stripping away methods like Stream(). I ran into a similar unhandled Promise exception w Node 7.5 and pg-live-select. However it was intermittent because of the way the net reference was being passed around. I ended up using V8 inspector and putting a 'debugger' statement directly above line 13 in connection.js to catch the corruption.
node_modules/lib/connection.js:13
this.stream = config.stream || new net.Stream();
^
TypeError: net.Stream is not a constructor
at new Connection (node_modules/pg-live-select/node_modules/pg/lib/connection.js:13:34)
at new Client (node_modules/pg-live-select/node_modules/pg/lib/client.js:26:37)
at Object.create (node_modules/pg-live-select/node_modules/pg/lib/pool.js:27:24)
at Pool._createResource (node_modules/generic-pool/lib/generic-pool.js:325:17)
at Pool.dispense [as _dispense] (node_modules/generic-pool/lib/generic-pool.js:313:12)
at Pool.acquire (node_modules/generic-pool/lib/generic-pool.js:388:8)
at Pool.pool.connect (node_modules/pg-live-select/node_modules/pg/lib/pool.js:78:14)
at PG.connect (node_modules/pg-live-select/node_modules/pg/lib/index.js:49:8)
at LivePg._updateQuery (node_modules/pg-live-select/index.js:295:6)
at node_modules/pg-live-select/index.js:160:14
at Array.forEach (native)
at Timeout.performNextUpdate [as _onTimeout] (node_modules/pg-live-select/index.js:159:23)
at ontimeout (timers.js:365:14)
at tryOnTimeout (timers.js:237:5)
at Timer.listOnTimeout (timers.js:207:5)

Redshift data access from node jdbc

I am getting below error when I try to data from redshift with the below mentioned code
var jdbc = new ( require('jdbc') );
var config = {
libpath: 'C:/Users/ABCD/Desktop/jar/RedshiftJDBC41-1.1.6.1006.jar',
//libs: [__dirname + 'path/to/other/jars.jar'],
drivername: 'com.amazon.redshift.jdbc41.Driver',
url: 'jdbc:redshift://examplecluster.abc123xyz789.us-west-2.redshift.amazonaws.com:5439/dev',
user: 'xxxx',
password: 'xxxxx'
};
jdbc.initialize(config, function(err, res) {
if (err) {
console.log(err);
}
});
var genericQueryHandler = function(err, results) {
if (err) {
console.log(err);
} else if (results) {
console.log(results);
}
jdbc.close(function(err) {
if(err) {
console.log(err);
} else {
console.log("Connection closed successfully!");
}
});
};
jdbc.open(function(err, conn) {
if (conn) {
// SELECT statements are called with executeQuery
jdbc.executeQuery("select * from information_schema.tables", genericQueryHandler);
}
});
Error:
C:\Users\ABCD> node redshift.js
C:\Users\ABCD\node_modules\jdbc\lib\jdbc.js:62>
if(this._props.getPropertySync('user') === undefined){>
^ TypeError: undefined is not a function
at JDBCConn.initialize
(C:\Users\ABCD\node_modules\jdbc\lib\jdbc.js:62:20)
at Object.<anonymous>
(C:\Users\ABCD\Desktop\AngularJS\redshift.js:15:6)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
Could you please let me know whether there is nay issue with the above mentioned node jdbc usage for redshift?
Please be aware that this answer applies to node-jdbc 0.0.15 and earlier only. It will not work for node-jdbc 0.1.1 or later, as the API has been completely reworked and is not backwards-compatible.
Try replacing the two lines in your configuration
user: 'xxxx',
password: 'xxxxx'
with
properties: [
['user', 'xxxx'],
['password', 'xxxxx']
]
I got the same error as you attempting to use Node to connect to a local Oracle XE database. After making the change above I was able to connect. I don't believe the error you are getting is specific to RedShift - I believe it affects all databases.
Note that the properties above have to be specified as an array of 2-element arrays. An object such as the following would seem the obvious way to specify the properties, but it doesn't work:
// Don't do this, it doesn't work.
properties: {
user: 'xxxx',
password: 'xxxxx'
}
To be honest, the fix I've proposed above is a workaround. I only found it by reading the source of the jdbc module. I can't say I'm terribly impressed with this module, what with the example code given in the documentation not working, and with a somewhat counter-intuitive and undocumented format for specifying custom properties.

Resources