Connection cannot be established to FTP server using nodejs - javascript

I´m currently trying to connect to a FTP server using the nodeJS lib basic-ftp. It seems that a connection was established, but I cannot perform a single operation or even output a log statement after trying to access the server. The code then runs into an timeout.. I can ping the server from my local environment using Windows CMD ping command..
const ftp = require("basic-ftp")
example()
async function example() {
const client = new ftp.Client(timeout = 30000)
client.ftp.verbose = true
try {
await client.access({
host: "10.xxx.xx.xx",
port: 2222,
user: "xxx",
pass: "xxxx",
secure: true
})
console.log("CONNECTED");
console.log(await client.ensureDir("/PATH/"));
console.log(await client.list('/PATH/'));
}
catch (err) {
console.log(err)
}
client.close()
}
Output:
Connected to 10.xxx.xx.xxx:2222 (No encryption)
< SSH-2.0-WS_FTP-SSH_8.5.0
Error: Timeout (control socket)
at Socket.<anonymous> (C:\Users\xxx\dev\nodejs\ftpTest\node_modules\basic-ftp\dist\FtpContext.js:316:58)
at Object.onceWrapper (events.js:299:28)
at Socket.emit (events.js:210:5)
at Socket._onTimeout (net.js:469:8)
at listOnTimeout (internal/timers.js:531:17)
at processTimers (internal/timers.js:475:7)
There is almost no output that helps me to identify the issue. I can establish a connection using WinSCP.
Does someone have an idea what could cause the problem and which steps are required to identify what could cause this issue?
Thanks a lot!
EDIT:
Could it be that there is some kind of key exchange missing? I had to click yes when using WinSCP!

Related

Node MariaDB stuck on getConnection

I'm running mariadb locally and want to query for a few rows using the Node driver.
I have the following code below that comes straight from the mariadb node docs. I've confirmed my server is up and running and that I can query from the CLI itself.
The weird thing is that the script doesn't fail or throw error. It just gets stuck at the await pool.getConnection() line. I even waited for like 5 minutes.
My server version is Server version: 10.7.3-MariaDB Homebrew and I'm using the 3.0.0 package version for Node https://www.npmjs.com/package/mariadb
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: 'localhost',
user: 'node',
password: 'PWD',
connectionLimit: 5,
port: 3306,
database: 'DB',
acquireTimeout: 5000
});
(async () => {
console.log('in iife');
let conn;
try {
console.log('awaiting conn');
//This never gets reached..just gets stuck even after 5s
conn = await pool.getConnection();
console.log(conn);
console.log('awaiting q');
const rows = await conn.query("SELECT * FROM foo where id=1");
console.log(rows);
} catch (err) {
throw err;
} finally {
if (conn) return conn.end();
}
})();
I've actually tried this on two separate devices and have the same exact issue.
Any ideas?
It was a red herring. Using dev tools to debug led me to realize there was a mundane runtime error in undeclared var. Red herring was that error was being caught and thrown. But bc this was being called as ad-hoc script, I was never aware of what the error was. Replacing the throw with a console.error led me to see error

How to connect nodejs redis client to redis cloud server?

const redis = require('redis');
const client = redis.createClient({
host: 'redis-19606.redislabs.com',
port: 19606,
password: 'password'
});
client.on('ready', () => {
console.log('redis is connected');
});
client.on('error', (err) => {
console.log('redis is disconnected: ', err);
});
(async () => {
try {
await client.connect();
} catch (error) {
console.error('error while connecting redis', error);
}
})();
This somehow does not seem to work. What am I doing wrong? It keeps connecting to 127.0.0.1:6379 which is the default config instead of what I am passing. This is only happening with nodejs client of redis. go-redis the golang client for redis is working flawlessly.
Just a guess, but which Node Redis version do you use? I had difficulties upgrading myself. The configuration of the client has changed since version 4.x.x. Since version 4.x.x you have to use a confiuration according to Client Configuration. Therefore use
const client = redis.createClient({
socket: {
host: 'redis-19606.redislabs.com',
port: 19606,
}
});
or use a URL
const client = redis.createClient({
url: "redis://redis-19606.redislabs.com:19606"
});
Your client configuration matches the Node Redis version 3.x.x but not 4.x.x. Please see Redis NPM v3.1.2 and Redis NPM v4.0.1 for details.
you should maintain this format of Redis connecting string:
redis://:YOUR_PASSWORD#YOUR_ENDPOINT:YOUR_PORT
What version of redis are you using?
Do not explicitly conect to redis by writing "client.connect()" but
instead use this after setting host, port and password:
redisClient.on("connect", () => {})
and then you can use redisClient variable to get and set values.
Also if you're trying to connect to a redislabs server then I think your host name might be incorrect and double check your host from redislabs.
Try this new Redis("redis://username:authpassword#127.0.0.1:6380/4");
Check the documentation Link

Connecting code to MongoDB database gives error: Error: querySrv ENODATA _mongodb._tcp.cluster0.h5prp.mongodb.net

I'm coding a discord bot and I want to connect it to a mongoDB database. However when doing this, I get this error,
Error: querySrv ENODATA _mongodb._tcp.cluster0.h5prp.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (node:dns:228:19) {
errno: undefined,
code: 'ENODATA',
syscall: 'querySrv',
hostname: '_mongodb._tcp.cluster0.h5prp.mongodb.net'
}
Here is my code:
client.on('ready', () => {
console.log('The bot is ready!')
const dbOptions = {
// These are the default values
keepAlive: true
}
new WOKCommands(client, {
// The name of the local folder for your command files
commandsDir: path.join(__dirname, 'commands'),
// Allow importing of .ts files if you are using ts-node
typeScript: true,
// Pass in the new dbOptions
dbOptions,
// Pass in your own mongo connection URI
mongoUri: 'mongodb+srv://discordbot:******#cluster0.h5prp.mongodb.net/myFirstDatabase?retryWrites=true&w=majority'
})
})
I looked through documentation and other posts but could not find anything that solves my problem.
I'm using Node.js v17.1.0. I'm using WOKCommands and following this tutorial series https://youtube.com/playlist?list=PLaxxQQak6D_f4Z5DtQo0b1McgjLVHmE8Q
I've allowed all IP Addresses to access my database, I've ensured my IP address is whitelisted
Any help appreciated.
Thanks
I needed to change the mongoDB connection URI to an earlier Node.js version.
I changed it to version '2.2.12 or later' and it worked.
Which game me a link like this:
mongodb://discordbot:<password>#cluster0-shard-00-00.h5prp.mongodb.net:27017,cluster0-shard-00-01.h5prp.mongodb.net:27017,cluster0-shard-00-02.h5prp.mongodb.net:27017/myFirstDatabase?ssl=true&replicaSet=atlas-g86xz1-shard-0&authSource=admin&retryWrites=true&w=majority

SequelizeConnectionError in Node.js application

I have strange problem and don't know in what place is the problem. I will be grateful for any help.
I have Node.js application which works fine in local windows 10 computer. I run this application successfully in Docker which is in CentOS server. This application works with remote MySQL and PostgreSQL databases. It worked correctly several days but yestoday I notice that I have error. Application can't connect to remote MySQL database anymore. In the same time I can connect to that remote MySQL database without any problem if I run application in my local computer or connect by DBeaver/dbForge tool.
MySQL.js:
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database_name', 'username', 'password', {
host: 'host',
dialect: 'mysql'
});
sequelize.authenticate().then(() => {
console.log('Connection to database has been established successfully.');
}).catch(err => {
console.error('Unable to connect to database:', err);
});
module.exports = sequelize;
routes.js:
const express = require('express');
const router = express.Router();
const sequelize = require('../configurations/MySQL');
const Sequelize = require('sequelize');
const passport = require('passport');
require('../configurations/password')(passport);
router.post('/search_by_name', passport.authenticate('jwt', {session: false}, null), function(req, res) {
const token = getToken(req.headers);
if (token) {
sequelize.query("LONG SQL QUERY", {
replacements: {
name: req.body.name,
},
type: Sequelize.QueryTypes.SELECT
}).then((locations) => {
res.status(200).send(locations)
}).catch((error) => {
res.status(400).send(error);
});
} else {
return res.status(401).send({
status: false,
description: "Unauthorized"
});
}
});
As you can see I use sequelize library to connect application to remote MySQL database. The same library I use to connect to remote PostgreSQL database. As I said before error happens only when I try to connect to remote MySQL database in Docker. There is no error with PostgreSQL connection in Docker. Is it possible that problem inside Docker/network?
Dependencies:
"sequelize": "^4.42.0"
"mysql2": "^1.6.4"
I also thought that the reason of the problem can be because of much pools/connections and sequelize library don't close them automatically. For thats why I restarted docker сontainer several times hoping to confirm the theory. Unfortunately the error do not disappear.
How do you think, what happens?
Error:
Unable to connect to the database: { SequelizeConnectionError: connect ETIMEDOUT
at Utils.Promise.tap.then.catch.err (/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:149:19)
at tryCatcher (/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/node_modules/bluebird/js/release/promise.js:512:31)
at Promise._settlePromise (/node_modules/bluebird/js/release/promise.js:569:18)
at Promise._settlePromise0 (/node_modules/bluebird/js/release/promise.js:614:10)
at Promise._settlePromises (/node_modules/bluebird/js/release/promise.js:690:18)
at _drainQueueStep (/node_modules/bluebird/js/release/async.js:138:12)
at _drainQueue (/node_modules/bluebird/js/release/async.js:131:9)
at Async._drainQueues (/node_modules/bluebird/js/release/async.js:147:5)
at Immediate.Async.drainQueues [as _onImmediate] (/node_modules/bluebird/js/release/async.js:17:14)
at processImmediate (timers.js:632:19)
name: 'SequelizeConnectionError',
parent:
{ Error: connect ETIMEDOUT
at Connection._handleTimeoutError (/node_modules/mysql2/lib/connection.js:173:17)
at listOnTimeout (timers.js:324:15)
at processTimers (timers.js:268:5)
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true },
original:
{ Error: connect ETIMEDOUT
at Connection._handleTimeoutError (/node_modules/mysql2/lib/connection.js:173:17)
at listOnTimeout (timers.js:324:15)
at processTimers (timers.js:268:5)
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true }}
Try to add pool option when new Sequelize. Reference document
Sequelize will setup a connection pool on initialization so you should
ideally only ever create one instance per database if you're
connecting to the DB from a single process. If you're connecting to
the DB from multiple processes, you'll have to create one instance per
process, but each instance should have a maximum connection pool size
of "max connection pool size divided by number of instances". So, if
you wanted a max connection pool size of 90 and you had 3 worker
processes, each process's instance should have a max connection pool
size of 30.
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database_name', 'username', 'password', {
host: 'host',
dialect: 'mysql',
pool: {
max: 15,
min: 5,
idle: 20000,
evict: 15000,
acquire: 30000
},
});
module.exports = sequelize;
Also, you can check more option at here
options.pool sequelize connection pool configuration
options.pool.max default: 5 Maximum number of connection in pool
options.pool.min default: 0 Minimum number of connection in pool
options.pool.idle default: 10000 The maximum time, in milliseconds,
that a connection can be idle before being released. Use with
combination of evict for proper working, for more details read
https://github.com/coopernurse/node-pool/issues/178#issuecomment-327110870
options.pool.acquire default: 10000 The maximum time, in milliseconds,
that pool will try to get connection before throwing error
options.pool.evict default: 10000 The time interval, in milliseconds,
for evicting stale connections. Set it to 0 to disable this feature.
options.pool.handleDisconnects default: true Controls if pool should
handle connection disconnect automatically without throwing errors
options.pool.validate A function that validates a connection. Called
with client. The default function checks that client is an object, and
that its state is not disconnected
In the simple terms i want to say that these type of error comes when your some configuration wrong entered. these are :
DB Name
Username
Password
so please cross verify your these things in your congif.json file
I would recommend to check the Database Hostname. Please try to resolve the hostname, if it is given IP address instead of domain. This would resolve the issue.

Error: connect ECONNREFUSED node.js https.get request

I'm running the following in a small test node project.
var https = require('https');
var request = https.get('https://example.com/script.json', function(response){
console.dir(response);
});
request.on('error', function(){
console.log(err);
});
When I try to console.dir the response I get the following error.
throw er; // Unhandles 'error' event
Error: connect ECONNREFUSED xxx.xx.xxx.xx:xxx
It's a simple get request to a json file on an external server. I know the file exists so I'm not sure why I'm getting the above error. The file can be run in the browser and requires no authentication.
UPDATE: I edited the code. created a promise and added an .on('error'... to catch any issues.
The following is now output:
( [Error: connect ECONNREFUSED xxx.xx.xxx.xx:xxx]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: 'xxx.xxx.xxx.xxx',
port: 443 )
Thanks to help from #robertklep I came up with the following solution which allows me to connect to HTTPS from behind a proxy using request
const https = require('https');
const request = require('request');
request(
{
'url':'https://https://example.com/script.json',
'proxy':'http://xx.xxx.xxx.xx'
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
);
The other server is not up, or not listening to 443 port so you get a connection refused.
Another option is that the nodejs app is resolving that example url differently to a different ip than your pc.

Categories