How to connect Redshift database using Node JS - node.js

I am not able to connect to the redshift database using Node. I am using Node JS version 14.15.1.
Is there any issue related to this version?
The following code, I have tried in my local machine,
redshift.js file
var Redshift = require('node-redshift');
var client = {
user: 'user',
database: 'db',
password: 'password',
port: port,
host: 'hostname',
};
var redshiftClient = new Redshift(client, {rawConnection:true});
module.exports = redshiftClient;
The following is the code to get the values from database,
index.js file
var redshiftClient = require('./redshift.js');
console.log('Before Connection');
redshiftClient.connect(function(err){
console.log('After Connection');
if(err) throw err;
else{
redshiftClient.query('SELECT * FROM "customer"', {raw: true}, function(err, data){
if(err) throw err;
else{
console.log(data);
redshiftClient.close();
}
});
}
});
If I run this code not getting the error and even this line is also not executed console.log('After Connection');

The package seems a bit abandoned as here's an open issue with exact issue
To solve that you need to apply this solution manually
go to node_modules/node-redshift and replace
"dependencies": {
"commander": "^2.9.0",
"migrate": "^0.2.2",
"pg": "^6.1.2",
"sql-bricks": "^1.2.3"
},
in package.json to
"dependencies": {
"commander": "^2.9.0",
"migrate": "^0.2.2",
"pg": "^8.1.5",
"sql-bricks": "^1.2.3"
},
run npm install in this directory in order to update this package. After that your code will work

This library is not very active, as mentioned above there's an open issue in github from 2020.
It's better to use pg-promise
Attaching a script link here.
https://www.javaniceday.com/post/how-to-connect-to-a-redshift-database-from-node-js

Related

loopback nodejs server not starting

I have project with nodejs loopback 3.x version and I am recently turned dev in nodejs. I have written the models, server aspects (server.js, server/root.js) etc. Following are the dependencies:
"dependencies" : {
"#types/async": "2.0.40",
"#types/lodash": "4.14.139",
"#types/loopback": "3.1.3",
"#types/loopback-boot": "2.23.0",
"loopback-connector-rest": "3.0.0",
"loopback-model-binder": "1.4.0",
"#types/multiparty": "0.0.31",
"rimraf": "2.6.1",
"sinon": "3.2.1",
"ts-node": "3.3.0",
"typescript": "2.8.3",
"gulp-sequence": "0.4.6",
"gulp-symlink": "2.1.4",
"gulp-typescript": "4.0.1",
"request": "2.81.0",
"shelljs": "0.8.1",
"yargs": "11.0.0",
"os-locale": "3.1.0",
"loopback-connector": "4.4.0",
"strong-globalize": "2.10.0",
"strong-remoting": "3.14.0"
}
This is my code snippet in server.ts:
const app: any = loopback();
boot(app, __dirname, (err) => {
if (err) throw err;
});
app.start = () => {
return app.listen(() => {
const BASE_URL = app.get('url').replace(/\/$/, '');
const explorer = app.get('loopback-component-explorer');
if (explorer) {
Logger.info(`Browse your REST API at ${BASE_URL}${explorer.mountPath}`);
}
});
};
Following are the steps for installing and starting app:
npm install
npm run build
npm run start
But the application is not starting, no errors but returns at command prompt. I enabled the verbose output for the npm run start -verbose command and I found following:
loopback:datasource Module ./connectors/rest not found, will try another candidate. +10ms
loopback:datasource Initializing connector RequestBuilder +561ms
loopback:datasource Connector is initialized for dataSource rest +7ms
loopback:datasource DataSource rest is now connected to undefined +1ms
lifecycle port-app#2.0.0~start: unsafe-perm in lifecycle true
Please let me know about any pointers regarding the above issue.
it was a silly miss from my part. Once you create the app and then in boot process you need to start the application.
boot(app, __dirname, (err) => {
if (err) throw err;
app.start(); // <-- Fix
});

Personality insight input var nodejs

var PersonalityInsightsV2 = require('watson-developer-cloud/personality-insights/v2');
var personality_insights = new PersonalityInsightsV2({
username: '<username>',
password: '<password>'
});
personality_insights.profile({
text: '<?php echo $_Session['description'];?>',
language: 'en' },
function (err, response) {
if (err)
console.log('error:', err);
else
console.log(JSON.stringify(response, null, 2));
});
It doesn't display anything. I have also done npm watson cloud and saved it, I have put my credentials and also forked it on git. What am I missing? I am a beginner but would love to use this on my page!
Here are the steps to run it locally, since you are a beginner I'll start from the beginning.
Create a new folder and name it whatever you want. Put these files in there.
Name the first file: index.js
fill in <YOUR-USERNAME>, <YOUR-PASSWORD>, and <YOUR-100-UNIQUE-WORDS> variables.
var express = require('express');
var app = express();
var http = require('http').Server(app);
var cfenv = require("cfenv");
var appEnv = cfenv.getAppEnv();
http.listen(appEnv.port, appEnv.bind);
var PersonalityInsightsV2 = require('watson-developer-cloud/personality-insights/v2');
var personality_insights = new PersonalityInsightsV2({
username: '<YOUR-USERNAME>',
password: '<YOUR-PASSWORD>'
});
personality_insights.profile({
text: "<YOUR-100-UNIQUE-WORDS>",
language: 'en' },
function (err, response) {
if (err)
console.log('error:', err);
else
console.log(JSON.stringify(response, null, 2));
});
Create another file and name it: package.json
put these contents in there
{
"name": "myWatsonApp",
"version": "1.0.0",
"description": "A Watson Personality Insights application",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"cfenv": "^1.0.3",
"express": "^4.13.4",
"watson-developer-cloud": "^2.2.0"
}
}
open your terminal and cd to the root of your folder you just created.
Run the command: npm install
Then run the command npm start
Your application will then be running and you will see output from the personality insights call you made in index.js

Node registry path with electron-updater and Sinopia

I am currently working on an application running on Electron (former atom-shell), and trying to design a way to alert the user when a new update is available. To do this, I am using electron-updater in the way described in electron-updater-sample. I also configured Sinopia to be listening on http://localhost:4873/ (default behavior) and ran this commande line:
npm config set registry "http://localhost:4873"
I checked in the .npmrc file, the registry is properly set with the new value.
The problem I have is when I try to check for the update, I get this error message in console:
{ [HTTPError: Response code 404 (Not Found)]
message: 'Response code 404 (Not Found)',
code: undefined,
host: 'registry.npmjs.org',
hostname: 'registry.npmjs.org',
method: 'GET',
path: '/hacker-keyboard-electron',
statusCode: 404,
statusMessage: 'Not Found' }
So I believe I forgot something in the configuration of npm that makes the application listen to the regular path for npm rather than the Sinopia server. The question is what?
Please find below the code I am using:
foobar-generator
├── app
├── bower components
├── bower.json
├── index.html
├── index. js
├── main. js
├── nbproject
├── node modules
├── npm-debug.log
├── package.json
├── readme. md
└── sinopia
package.json
{
"name": "foobar-generator",
"version": "0.0.1",
"description": "A generator for foobar",
"main": "main.js",
"dependencies": {
"angular": "^1.4.7",
"bootstrap": "^3.3.5",
"chokidar": "^1.2.0",
"electron-debug": "^0.2.1",
"electron-packager": "^5.1.0",
"electron-plugins": "^0.0.4",
"electron-prebuilt": "^0.33.6",
"electron-rebuild": "^1.0.2",
"electron-updater": "^0.2.0",
"grunt": "^0.4.5",
"jquery": "^2.1.4"
},
"devDependencies": {},
"publishConfig": {
"registry": "http://localhost:4873/"
},
"registry": "http://localhost:4873/"
}
main.js
var appli = require('app');
var BrowserWindow = require('browser-window');
var updater = require('electron-updater');
var util = require('util');
// Report crashes to our server.
require('crash-reporter').start();
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var mainWindow = null;
var loaded = false;
// Quit when all windows are closed.
appli.on('window-all-closed', function () {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
appli.quit();
}
});
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
appli.on('ready', function () {
updater.on('ready', function () {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600});
// and load the index.html of the app.
mainWindow.loadUrl('file://' + __dirname + '/index.html');
mainWindow.openDevTools({detach: true});
mainWindow.on('closed', function () {
mainWindow = null;
});
});
updater.on('updateRequired', function () {
appli.quit();
});
updater.on('updateAvailable', function () {
if (mainWindow) {
mainWindow.webContents.send('update-available');
}
});
updater.start();
updater.check(function (err, results) {
if (err) {
return console.error(util.inspect(err));
}
console.log(results);
});
});
Do you guys see anything I could have forgotten/done wrong?
By reading the manual for npmrc (npm help npmrc), I have discovered the the .npmrc file is not unique. By configuring the registry the way I did, I only changed the per-user .npmrc. But there also should be such a file in your project root directory! It is in this one that you should configure the registry you want to use. Adding this file in project root directory solved the problem I was facing.
You should listen to error event.
Try this
updater.on('error', function (err) {
console.log(err);
});

Npm install with success but nodejs cannot find module 'db'

This error is so common but although I searched a lot of similar questions I did not found a solution to my problem. I installed the module with no problems using "npm install db".
The "server.js" is in the same folder as"node_moludes" and NPM created a "db" folder inside "node_moludes" with all the content.
All NPM commands return success (install, link, list etc), I even added the module to my "package.json" and it also installs with no problem just using "npm install -d".
Despite it all, when I run the server, Nodejs can't find the 'db' module... any help?
nodejs version: 0.10.26
npm version: 1.4.3
server.js
var http = require('http'),
url = require('url'),
db = require('db');
var send = function(response, data){
response.writeHead(200, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin': '*'
});
response.end(JSON.stringify({data: data}));
};
http.createServer(function (request, response) {
var query = url.parse(request.url, true).query;
if(query.set) {
db.set(query.set, query.val || '');
send(response, true);
} else if (query.get) {
db.get(query.get, function(data){
send(response, data);
});
} else send(response, query);
}).listen(80);
package.json
{
"name": "xxxxx",
"version": "0.0.1",
"author": "rafaelcastrocouto",
"repository": "git://github.com/rafaelcastrocouto/xxxxx",
"dependencies": {
"db": ">= 1.00.x"
},
"engine": "node >= 0.10.x"
}
It appears the db module was setup without following some Node.js norms. It doesn't contain an index.* file or specify a "main" setting in its package.json to direct Node otherwise.
You should be able to reference the main file within the package directly:
var db = require('db/db');

Error trying to connect to MongoHQ database from node.js app

Can't seems to understand what is the problem.
var MongoClient = require('mongodb').MongoClient;
console.log('Trying to connect with', settings );
MongoClient.connect( settings.mongourl, settings.options, function(err, db) {
if(!err) {
console.log("We are connected");
callback( true, db );
}
else {
console.log("Connection failed", err );
callback( false, null );
}
});
In result I get (changed some parts to xxxx):
Trying to connect with { mongourl: 'mongodb://xxxx:xxxx#xxxx.mongohq.com:xxxx/testdb', options: {auto_reconnect: true}}
Connection failed [Error: failed to connect to [xxxx.mongohq.com:xxxx]]
I have doublechecked the url string for connection, everything is ok, tried to create another user just for testing - still getting errors. The worst part is that the description in error doesn't give any hint what cause the problem.
Just in case, my package.json dependancy part:
"dependencies": {
"fetch": "~0.3.6",
"mongodb": "~1.4.3",
"connect-mongo": "~0.4.1",
"amqp": "~0.2.0",
"express": "~4.1.1",
"express-session": "~1.0.4",
"connect": "~2.15.0"
}
Use the same connection string and try to connect using mongo client.
mongo --host "xxxx.mongohq.com" --port "XXXX" --username "" -p ""
See if you can connect thru the shell or not.
For more info look here: http://docs.mongodb.org/v2.2/reference/mongo/#bin.mongo

Resources