How can i fix this call back error in Node.js? - node.js

At first, I installed this library,
> npm install rocketchat-api
and then I've ran this code to use rocket.chat REST API
// Node.js code
const RocketChatApi = require('rocketchat-api');
const result='https://rocket.chat/docs/developer-guides/rest-api/users/setavatar';
const userId='A user id';
const avatarUrl='http://www.coca.ir/wp-content/uploads/2017/05/flowers-love-profile-pictures-1.jpg'
const rocketChatClient = new RocketChatApi(
'https',
'rocket.chat',
443,
'username',
'password',
(err, result)=>{
console.info('RC connected', result)
});
rocketChatClient.users.setAvatar(userId, avatarUrl, (err, body)=>{
});
After run this in Node.js, I got following error, anyone can help me?
\node_modules\rocketchat-api\lib\net.js:144
return callback ? callback(error, null) : reject(error);
^
TypeError: callback is not a function
at Request.clientRequest [as _callback] (D:\node js projects\rocketTest\node_modules\rocketchat-api\lib\net.js:144:39)
at self.callback (D:\node js projects\rocketTest\node_modules\request\request.js:185:22)
at Request.emit (events.js:198:13)
at ClientRequest.<anonymous> (D:\node js projects\rocketTest\node_modules\request\request.js:819:16)
at Object.onceWrapper (events.js:286:20)
at ClientRequest.emit (events.js:198:13)
at TLSSocket.emitRequestTimeout (_http_client.js:662:40)
at Object.onceWrapper (events.js:286:20)
at TLSSocket.emit (events.js:198:13)
at TLSSocket.Socket._onTimeout (net.js:442:8)
at ontimeout (timers.js:436:11)
at tryOnTimeout (timers.js:300:5)
at listOnTimeout (timers.js:263:5)
at Timer.processTimers (timers.js:223:10)

That's because setAvatar() only accepts 2 parameters: avatarUrl and callback. If you pass 3 parameters, it would take the second one as callback, and throw TypeError if it is not a function (In your example, the 2nd parameter avatarUrl is a string).
Please refer to the source code of lib/api/users.js in rocketchat-api source code:
setAvatar (avatarUrl, callback) {
return this.client.request("POST", "users.setAvatar", {
avatarUrl
}, callback);
}
Unfortunately, the rocketchat-api module's document is incorrect, which leads the problem.

Related

Getting "InternalServerError" while using Mongo with Node js

I am new to Node js programming. Trying to write a simple user create using.. code along with the stack track is given below. Appreciate any help as to what is causing this..
users-add.mjs:
'use strict';
const util = require('util');
const restify = require('restify-clients');
console.log("starting...");
var client = restify.createJsonClient({url: 'http://localhost:'+process.env.PORT, version: '*'});
console.log("starting...2 ");
client.basicAuth('them', 'D4ED43C0-8BD6-4FE2-B358-7C0E230D11EF');
client.post('/create-user', { username: "me", password: "w0rd", provider: "local",
familyName: "GUD", givenName: "RG", middleName: "Ud", emails: [], photos: []},
(err, req, res, obj) => {
console.log("starting...4 ");
if(err) {
console.log("starting...5");
console.error(err.stack);
}
else {
console.log("starting...6");
console.log('Created ' + util.inspect(obj));
}
});
console.log("starting...3 ");
Here is the error I'm getting.. Surprisingly the server side code is able to insert the record into MongoDB, and yet I get this error..
InternalServerError: {}
at Object.createHttpErr (/Users/raviguduru/node-web-dev/chapter8/users/node_modules/restify-clients/lib/helpers/errors.js:91:26)
at ClientRequest.onResponse (/Users/raviguduru/node-web-dev/chapter8/users/node_modules/restify-clients/lib/HttpClient.js:309:26)
at Object.onceWrapper (events.js:300:26)
at ClientRequest.emit (events.js:210:5)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:583:27)
at HTTPParser.parserOnHeadersComplete (_http_common.js:115:17)
at Socket.socketOnData (_http_client.js:456:22)
at Socket.emit (events.js:210:5)
at addChunk (_stream_readable.js:309:12)
at readableAddChunk (_stream_readable.js:290:11)
Pls help.
This problem is solved now.. The internal server error comes when we have MongoDBClient calls not wrapped in try/catch blocks. After I included try/catch blocks, they went away.

Unknown command when using promise-ftp in node

I'm trying to use a promise approach when interacting with my ftp server. I'm using the node package 'promise-ftp' v1.3.5.
The code I have is as follows:
const appFeedBuffer = Buffer.from('somedatastring', 'utf8');
var Client = require('promise-ftp');
var ftpClient = new Client();
ftpClient.connect({ host: 'myHost', user: 'me', password: 'mypassword' })
.then(() => {
return ftpClient.mkdir('newDir')
}).then(() => {
return ftpClient.put(appFeedBuffer, 'fileName')
}).then(()=> {
return ftpClient.rmdir('oldDir')
}).then(() => {
return ftpClient.rename('newDir', 'oldDir')
}).then(() => {
return ftpClient.end();
}).catch(err => {
console.log("something went wrong: " + err);
res.status(500).send('SERVER ERROR');
});
The problem is the put command - I get the error 'UNKNOWN COMMAND' which appears to come from the #icetee/ftp library, of which promise-ftp is a dependant. put is most certainly a valid command in the promise-ftp library!
Stack:
Unhandled rejection Error: Unknown command
at makeError (/Users/projects/ftpProject/node_modules/#icetee/ftp/lib/connection.js:1128:13)
at Parser.<anonymous> (/Users/projects/ftpProject/node_modules/#icetee/ftp/lib/connection.js:122:25)
at emitTwo (events.js:126:13)
at Parser.emit (events.js:214:7)
at Parser._write (/Users/projects/ftpProject/node_modules/#icetee/ftp/lib/parser.js:61:10)
at doWrite (_stream_writable.js:397:12)
at writeOrBuffer (_stream_writable.js:383:5)
at Parser.Writable.write (_stream_writable.js:290:11)
at Socket.ondata (/Users/projects/ftpProject/node_modules/#icetee/ftp/lib/connection.js:298:20)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at addChunk (_stream_readable.js:263:12)
at readableAddChunk (_stream_readable.js:250:11)
at Socket.Readable.push (_stream_readable.js:208:10)
at TCP.onread (net.js:597:20)
I can't find anyone else having this problem. What am I doing wrong?

trying to connect SQL using node js

app.get('/', function (req, res) {
var config = {
user: 'sa',
password: '',
server: 'localhost',
database: 'TestDB'
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from userInfo', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
console.log(recordset);
});
});
});
Getting this error in command prompt
{ Error: Failed to connect to localhost:1433 - Could not connect (sequence)
at Connection.tedious.once.err (D:\Nodejs\UsersCreate\node_modules\mssql\lib\tedious.js:216:17)
at Object.onceWrapper (events.js:293:19)
at emitOne (events.js:96:13)
at Connection.emit (events.js:191:7)
at Connection.socketError (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connection.js:875:14)
at D:\Nodejs\UsersCreate\node_modules\tedious\lib\connection.js:740:25
at SequentialConnectionStrategy.connect (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connector.js:153:9)
at Socket.onError (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connector.js:169:16)
at emitOne (events.js:96:13)
at Socket.emit (events.js:191:7)
code: 'ESOCKET',
originalError:
{ ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at ConnectionError (D:\Nodejs\UsersCreate\node_modules\tedious\lib\errors.js:12:12)
at Connection.socketError (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connection.js:875:30)
at D:\Nodejs\UsersCreate\node_modules\tedious\lib\connection.js:740:25
at SequentialConnectionStrategy.connect (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connector.js:153:9)
at Socket.onError (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connector.js:169:16)
at emitOne (events.js:96:13)
at Socket.emit (events.js:191:7)
at emitErrorNT (net.js:1284:8)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
message: 'Failed to connect to localhost:1433 - Could not connect (sequence)',
code: 'ESOCKET' },
name: 'ConnectionError' }
{ ConnectionError: Connection is closed.
at Request._query (D:\Nodejs\UsersCreate\node_modules\mssql\lib\base.js:1299:37)
at Request._query (D:\Nodejs\UsersCreate\node_modules\mssql\lib\tedious.js:497:11)
at Request.query (D:\Nodejs\UsersCreate\node_modules\mssql\lib\base.js:1242:12)
at D:\Nodejs\UsersCreate\app.js:118:17
at _poolCreate.then.catch.err (D:\Nodejs\UsersCreate\node_modules\mssql\lib\base.js:269:7)
at process._tickCallback (internal/process/next_tick.js:109:7) code: 'ECONNCLOSED', name: 'ConnectionError' }
undefined
Please help me on this error and need navigation to rectify this error

Cloud Functions for Firebase Image download function Error

I am building a web application using Firebase and the new feature Cloud Functions for Firebase. I have created a function that takes a URL and downloads the image into a 64-bit encoded string as below using the node modules request and request-promise-native:
module.exports = {
downloadImageFromUrl: function (url) {
var options = {
method: 'GET',
uri: url,
resolveWithFullResponse: true,
simple: false,
family: 4
};
return rp.get(options)
.then(function (res) {
return "data:" + res.headers["content-type"] + ";base64," + new Buffer(res.body).toString('base64');
})
.catch(function (error) {
console.log("ERROR GETTING image", error);
return error;
});
}
};
The top function works perfectly running locally but once on firebase it gives the error:
RequestError: Error: getaddrinfo EAI_AGAIN lh6.googleusercontent.com:443
at new RequestError (/user_code/node_modules/request-promise/node_modules/request-promise-core/lib/errors.js:14:15)
at Request.plumbing.callback (/user_code/node_modules/request-promise/node_modules/request-promise-core/lib/plumbing.js:87:29)
at Request.RP$callback [as _callback] (/user_code/node_modules/request-promise/node_modules/request-promise-core/lib/plumbing.js:46:31)
at self.callback (/user_code/node_modules/request/request.js:188:22)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at Request.onRequestError (/user_code/node_modules/request/request.js:884:8)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:188:7)
at TLSSocket.socketErrorListener (_http_client.js:310:9)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:188:7)
at connectErrorNT (net.js:1020:8)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickDomainCallback (internal/process/next_tick.js:122:9)
I am calling the function in the firebase auth trigger when a user is created as below:
exports.createUser = functions.auth.user().onCreate(event => {
if (event.data.photoURL) {
utils.downloadImageFromUrl(event.data.photoURL)
.then(function(res){
console.log("User Photo", res);
})
.catch(function(error){
console.log("Error", error);
})
}
});
Any help would be greatly appreciated.
Not entirely sure yet if this is the answer, but after reading the documentation, I read their free plan which says you cannot make any out bound requests. So I guess getting an image from a Url counts as an outbound request. After I start paying for their service, I will come back to verify if this was the problem.

Mongoose .save() -- TypeError: _this[i].emit is not a function

When attempting to save a document this error is thrown:
/Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/node_modules/mongodb/lib/utils.js:98
process.nextTick(function() { throw err; });
^
TypeError: _this[i].emit is not a function
at EventEmitter.notify (/Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/lib/types/documentarray.js:238:18)
at emitOne (events.js:82:20)
at EventEmitter.emit (events.js:169:7)
at Document.(anonymous function) [as emit] (/Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/lib/document.js:93:44)
at EventEmitter.<anonymous> (/Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/lib/schema/embedded.js:31:15)
at emitTwo (events.js:92:20)
at EventEmitter.emit (events.js:172:7)
at model.Document.(anonymous function) [as emit] (/Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/lib/document.js:93:44)
at /Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/lib/model.js:227:11
at /Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/lib/model.js:135:7
at /Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/node_modules/mongodb/lib/collection.js:504:5
at /Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/node_modules/mongodb/lib/collection.js:666:5
at handleCallback (/Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/node_modules/mongodb/lib/utils.js:96:12)
at /Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js:473:9
at handleCallback (/Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/node_modules/mongodb/lib/utils.js:96:12)
at resultHandler (/Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js:420:5)
at commandCallback (/Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:1246:9)
at Callbacks.emit (/Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:119:3)
at null.messageHandler (/Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:397:23)
at Socket.<anonymous> (/Users/home/Documents/web/thp/modules/thp_db/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js:302:22)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at readableAddChunk (_stream_readable.js:153:18)
at Socket.Readable.push (_stream_readable.js:111:10)
at TCP.onread (net.js:536:20)
Code leading to save looks like this:
var db = req.app.locals.db;
var league = new db.League();
// league is populated here
// ================
// GIVE LEAGUE _id (auto increment)
// ================
db.Counter.findByIdAndUpdate('League',
{ $inc: { n: 1 } },
{ new: true },
function(err, counter){
if(err) return log.error('League _id set error', err);
league._id = counter.n;
// ================
// INTO DB: CODE RUNS TO HERE
// ================
league.save(function(err, new_league) {
// DOES NOT REACH HERE!
if (err) {
log.error('league DB entry error:', err);
return res.status(200).end('Error creating league');
}
console.log('SAVED LEAGUE', util.inspect(new_league, false, null));
res.status(200).end('Thank you');
});
}
);
Strange thing is that this worked fine last night, and unless I sleepwalked and logged in, nothing was changed.
the db variable is a collection of models.
Any help would be much appreciated.
Turns out that the error is thrown depending on which inputs of the submission form are filled out. Haven't the time to determine which exactly at the moment, but will update here when I do.
UPDATE: my league var was populated by a JSON object parsed from incoming form data. One of the properties was thoughtlessly called .on, which was fooling with the standard event listening notation .on. Silly mistake! Always is.

Resources