Can't connect to Tarantool container inside Docker through Nodejs - javascript

I want to connect to the tarantool cotainer using this code:
import TarantoolConnection from 'tarantool-driver'
let connection = new TarantoolConnection('192.168.99.100:3301');
connection.ping().then((res) => {
console.log(res);
});
Before that i started container:
docker run -p 3301:3301 -d tarantool/tarantool:1.6
But in result i get nothing.
If i try to create space or\and index for this space:
connection.eval("box.schema.space.create('myspace', {if_not_exists=true, temporary=true})").then((res) => {
console.log(res);
});
I get this error:
UnhandledPromiseRejectionWarning: Unhandled promise
rejection (rejection id: 1): Error: This socket is closed
or:
UnhandledPromiseRejectionWarning: Unhandled promise
rejection (rejection id: 2): Error: connection will be destroyed or
already destroyed, create another one
As i see from the error, the needed socket is already closed, but i don't understand why.
Version of tarantool driver:
"tarantool-driver": "2.0.5",
How can i fix it?

You have two problems here:
You should connect to localhost:3301 instead of 192.168.99.100:3301
You have to use connection.connect() before connection.ping() or connection.eval()
Here is the working code:
const TarantoolConnection = require('tarantool-driver');
let connection = new TarantoolConnection({port: 3301});
connection.connect().then((res) => {
console.log("Connected: " + res);
connection.ping().then((res) => {
console.log("Pong: " + res);
});
connection.eval("box.schema.space.create('myspace', {if_not_exists=true, temporary=true})").then((res) => {
console.log("Space created");
});
});
Just in case, I've used the following command to start tarantool docker instance:
$ docker run --rm -p 3301:3301 -t -i tarantool/tarantool:1.6

Related

Is it possible to run Jest in Azure function runtime?

This might be a case of 'you're using the wrong tools for the job' but I'm going to shoot my question anyways, because this is what I have to work with for now.
So, here goes:
I have to make relatively small applications that periodically run as functions in an Azure environment. These applications perform tasks like fetching data from an API and storing that data on a SFTP server. When I create these applications I use a TDD approach with Jest.
I'd like to react to any problems proactively and solve them before the function runs are scheduled. If I run Jest locally I would notice any of these problems but I'd like to automate this proces. Therefor I'd like to know if it's possible to run these tests from an Azure function and have Azure Warnings notify me when one these runs fail.
What have I tried?
Created new function folder "Jest_Function"
Added an always failing test in a separate file.
/main_functions_folder
/jest_function
- index.js
- function.json
- failingTest.test.js
added the following code to index.js:
const { exec } = require('child_process');
function checkTests() {
return new Promise((resolve, reject) => {
exec('npm run test failingTest.test.js', (error) => {
if (error) reject(error);
else resolve();
});
});
}
module.exports = async function (context) {
try {
await checkTests();
} catch (err) {
context.log('tests failed!');
throw err;
}
};
Transforming the function and running it in the terminal results in expected behaviour:
const { exec } = require('child_process');
function checkTests() {
return new Promise((resolve, reject) => {
exec('npm run test failingTest.test.js', (error) => {
if (error) reject(error);
else resolve();
});
});
}
async function myTest() {
try {
await checkTests();
} catch (err) {
console.log('tests failed!');
throw err;
}
}
myTest();
tests failed!
node:child_process:399
ex = new Error('Command failed: ' + cmd + '\n' + stderr);
^
Error: Command failed: npm run test failingTest.test.js
FAIL jest_function/failingTest.test.js
✕ short test (3 ms)
● short test
expect(received).toBe(expected) // Object.is equality
Expected: 1
Received: 0
1 | test('short test', () => {
> 2 | expect(0).toBe(1);
| ^
3 | });
4 |
at Object.<anonymous> (jest_function/failingTest.test.js:2:13)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 0.227 s, estimated 1 s
Ran all test suites matching /failingTest.test.js/i.
at ChildProcess.exithandler (node:child_process:399:12)
at ChildProcess.emit (node:events:520:28)
at maybeClose (node:internal/child_process:1092:16)
at Process.ChildProcess._handle.onexit (node:internal/child_process:302:5) {
killed: false,
code: 1,
signal: null,
cmd: 'npm run test failingTest.test.js'
}
Azure
I deployed the function in Azure and manualy ran it. This resulted in a failing function as I expected, but for the wrong reason. It displayed the following error message:
Result: Failure Exception: Error: Command failed: npm run test failingTest.test.js sh: 1: jest: Permission denied
I'm not really sure where to go from here, any help or advice will be appreciated!
Not sure if you can use jest directly from within Functions but I know you can run pupeteer headless in Azure Functions:
https://anthonychu.ca/post/azure-functions-headless-chromium-puppeteer-playwright/
and there's also jest-pupeteer package but not sure if there is a specific limitation on jest in Functions if all of the deps are installed as runtime dependencies.
I was able to make this work using npx instead of npm:
const { exec } = require('child_process');
function checkTests() {
return new Promise((resolve, reject) => {
exec('npx jest jest_function/failingTest.test.js', (error) => {
if (error) reject(error);
else resolve();
});
});
}
module.exports = async function (context) {
try {
await checkTests();
} catch (err) {
context.log('tests failed!');
throw err;
}
};
Looking at the logs I'm not really sure what '330' exactly is, but is assume it is installing jest?
2022-04-19T09:54:06Z [Information] Error: Command failed: npx jest
npx: installed 330 in 32.481s
Anyways I'm glad I got this working now :).

I have an error for discord.js rpc! Can someone please help me?

This is my error:
(node:42087) UnhandledPromiseRejectionWarning: Error: Could not connect
at Socket.onerror (/Users/vinesh/RPC/node_modules/discord-rpc/src/transports/ipc.js:32:16)
at Object.onceWrapper (events.js:422:26)
at Socket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:42087) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:42087) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
My code:
const RPC = require('discord-rpc');
const client = new RPC.Client({ transport: 'ipc' });
client.on('ready', () =>
{
client.request('SET_ACTIVITY', {
pid: process.pid,
activity: {
assets: {
large_image: 'Coding'
},
details: 'Coding',
buttons: [
{ label: 'Emperor', url: 'https://dsc.gg/invite-emperor' },
{ label: 'https://dsc.gg/invite-emperor', url: 'https://dsc.gg/invite-emperor' }
]
}
});
console.log('started!');
});
client.login({ clientId: 'My_ID' });
How do I fix this? Is it because the code is old? I don't know why it does that. I did npm init -y, npm install discord, and npm install discord-rpc.
If you are running the web browser version of Discord, RPC will not work. Instead download Discord for Desktop which is here.
If you are running Discord desktop then try this code. Also remember to add your assets in https://discord.com/developers/applications/Application_ID/rich-presence/assets and make sure they are the same name in application and code. You need large_text so don't remove it.
var rpc = require("discord-rpc")
const client = new rpc.Client({ transport: 'ipc' })
client.on('ready', () => {
client.request('SET_ACTIVITY', {
pid: process.pid,
activity : {
details : "Coding",
assets : {
large_image : "Your Image",
large_text : "Your Status"
},
buttons : [{label : "Emperor" , url : "https://dsc.gg/invite-emperor"},{label : "Invite 2?",url : "https://dsc.gg/invite-emperor"}]
}
})
})
client.login({ clientId : "CLIENT_ID" }).catch(console.error);

Node UnhandledPromiseRejectionWarning when saving to MongoDb

New to node- I'm trying to save some of my tweets from Twitter API into mongo using Twit package.
I've connected to mongodb on port 27017 using mongoose, and this piece of code I've written seems to save the tweets to my db, however I seem to be getting this warning back everytime I save a document:
(node:9991) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 8)
Here is my code:
const Tweet = require('./app/models/tweet.model.js');
const dbConfig = require('./config/database.config.js');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect(dbConfig.url, {
useNewUrlParser: true
}).then(() => {
console.log("Successfully connected to the database");
}).catch(err => {
console.log('Could not connect to the database. Exiting now...', err);
process.exit();
});
var Twit = require("twit");
var config = require("./config/twitter.config");
var T = new Twit(config);
var params = {
screen_name: "decade3uk",
count: 2
};
T.get("statuses/user_timeline", params, gotData);
function gotData(err, data, response) {
var tweets = data;
for(var i=0;i<tweets.length;i++){
const tweet = new Tweet({
created_at:tweets[i].created_at,
id_str:tweets[i].id_str,
text:tweets[i].text
});
tweet.save()
.then(entry => {
response.send(entry);
}).catch(err => {
response.status(500).send({
message: err.message || "Some error occurred while creating the Tweet."
});
});
}
}
What is best practice to get rid of this error?
Why don't you try to find where is that exception coming from and what exactly it is. You can find that by adding the following code to your server file, just to make sure you get what's causing the exception.
process.on('unhandledRejection', (reason, promise) => {
console.log("Reason: ",reason,"promise: ",promise);
})

Mocha give too long error message when testing node.js

I am learning node.js and how to test functions. I have a problem when using mocha: when functions are passing test, everything is completely fine, I get a nice looking message.
But if whichever function which doesnt pass a test - for example the result in the test is 0 but intentionally I wrote the asswertion to expect 1 - it gives me a mile long error massage in the bash-cli-console:
Async functions
(node:6001) UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: 0 == 1
at utils.requestWikiPage.then.resBody (/home/sandor/Documents/learning-curve-master/node-dev-course/testing-tut/utils/utils.test.js:10:20)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
(node:6001) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:6001) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
1) it should return a html page
0 passing (2s)
1 failing
1) Async functions
it should return a html page:
Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/home/sandor/Documents/learning-curve-master/node-dev-course/testing-tut/utils/utils.test.js)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! dev-course#1.0.0 test: `mocha ./testing-tut/**/*.test.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the dev-course#1.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/sandor/.npm/_logs/2018-07-04T11_31_53_292Z-debug.log
[nodemon] app crashed - waiting for file changes before starting...
I dont know why do I get this part: UnhandledPromiseRejectionWarning...
and why do I get this part: npm ERR! code ELIFECYCLE
the function I am testing: (it makes a request to wikipedia for the wiki page of george washington and collects the html page from the response. On 'end' of the responses readstream it resolves the html page. The function works just fine)
// utils.js
function requestWikiPage() {
const reqOpts = {
hostname : 'en.wikipedia.org',
port : 443,
path : '/wiki/George_Washington',
method : "GET"
}
return new Promise(resolve => {
let req = https.request(reqOpts, (res) => {
let resBody = "";
res.setEncoding('utf-8');
res.on('data', (chunk) => {
resBody += chunk;
});
res.on('end', () => {
resolve(resBody);
});
});
req.on('err', (err) => {
console.log(err);
});
req.end();
});
}
module.exports.requestWikiPage = requestWikiPage;
Mocha code: (The 'resBody' variable is a string, containing a html page, where '' stays on the index of 0. In the assertion I test it for 1 to create an error message)
const utils = require('./utils');
var assert = require('assert');
describe('Async functions', function() {
it('it should return a html page', (done) => {
utils.requestWikiPage().then(resBody => {
assert.equal(resBody.indexOf('<!DOCTYPE html>'), 1);
done();
});
});
});
So I dont understand why do I get that long error message just because I expect to be not on the 0 index than on the first? (Actually I get that error message whith every function not just with this)
How can I set up mocha that it gives me a more minimal and intuitive error message.
Thanks a million for your answers
You need to properly reject the promise in #requestWikiPage if it doesn't resolve or there is an error, and then handle that rejection in your test. The following changes will likely solve the issue in your question (i.e. having mocha correctly handle a failed test without all the extra output), but the next step would obviously be getting your test to pass.
Notice we add the reject callback to our new Promise() and instead of console.log(err); below in your req.on('error'... callback, we now use reject as our error callback.
// utils.js
function requestWikiPage() {
const reqOpts = {
hostname : 'en.wikipedia.org',
port : 443,
path : '/wiki/George_Washington',
method : "GET"
}
return new Promise((resolve, reject) => {
let req = https.request(reqOpts, (res) => {
let resBody = "";
res.setEncoding('utf-8');
res.on('data', (chunk) => {
resBody += chunk;
});
res.on('end', () => {
resolve(resBody);
});
});
req.on('err', reject);
req.end();
});
}
module.exports.requestWikiPage = requestWikiPage;
And now handle if the promise is rejected via a catch block by using done as the catch callback (which would effectively pass the error to done which mocha requires).
const utils = require('./utils');
var assert = require('assert');
describe('Async functions', function() {
it('it should return a html page', (done) => {
utils.requestWikiPage().then(resBody => {
assert.equal(resBody.indexOf('<!DOCTYPE html>'), 1);
done();
}).catch(done);
});
});

Calling a promise in a test get error 400 in NodeJS

I'm trying to use Contentful, a new JS library for building static websites. I want to use it in Node JS.
I created an app file like this (the name is getContent.js):
'use strict';
var contentful = require('contentful')
var client = contentful.createClient({
space: '****',
accessToken: '****'
});
module.exports = client;
function getEntry() {
return client.getEntry('******')
.then(function (entry) {
// logs the entry metadata
console.log(entry.sys)
// logs the field with ID title
console.log(entry.fields.channelName)
})
}
Then I created a test (getContent.test.js) like this:
'use strict';
let chai = require('chai');
let should = chai.should();
var expect = chai.expect;
var rewire = require("rewire");
let getContent = rewire("./getContent.js");
describe('Retreive existing', () => {
it('it should succeed', (done) => {
getContent.getEntry({contentName:'****'
}, undefined, (err, result) => {
try {
expect(err).to.not.exist;
expect(result).to.exist;
// res.body.sould be equal
done();
} catch (error) {
done(error);
}
});
});
});
but I obtain this error:
Retreive existing (node:42572) UnhandledPromiseRejectionWarning:
Error: Request failed with status code 400
at createError (/Users/ire/Projects/SZDEMUX_GDPR/api/node_modules/contentful/dist/contentful.node.js:886:15)
at settle (/Users/ire/Projects/SZDEMUX_GDPR/api/node_modules/contentful/dist/contentful.node.js:1049:12)
at IncomingMessage.handleStreamEnd (/Users/ire/Projects/SZDEMUX_GDPR/api/node_modules/contentful/dist/contentful.node.js:294:11)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9) (node:42572) UnhandledPromiseRejectionWarning: Unhandled promise
rejection. This error originated either by throwing inside of an async
function without a catch block, or by rejecting a promise which was
not handled with .catch(). (rejection id: 3) (node:42572) [DEP0018]
DeprecationWarning: Unhandled promise rejections are deprecated. In
the future, promise rejections that are not handled will terminate the
Node.js process with a non-zero exit code.
Do you know what I'm missing? the promise is ok, I already tested it with a simple node getContent.js
I am seeing few issues with your code:
1. Invalid Args
In your test function, in getContent.js, you are passing an argument to the getEntry method (return client.getEntry('******'), whereas you are passing an object in the test (getContent.getEntry({}))
2. Mixing Promises & Callbacks
it('it should succeed', (done) => {
getContent.getEntry("****")
.then((result) => {
console.log(result);
try {
expect(result).to.exist;
// res.body.sould be equal
done();
} catch (error) {
done(error);
}
})
.catch(error => {
console.log(error);
done(error)
})
});
3. Source of Unhandled Promise rejection is not clear:
Is it coming from your test function in getContent.js, or, is it coming from your actual test?
Probably, this could also come from,
expect(err).to.not.exist;
expect(result).to.exist;
Always catch errors in Promises and reject it with proper reason to avoid issues like this.
Could you please update your code and repost it, so that its clear for other users?

Categories