Very large object dumped on each request - node.js

I have an application that I'm writing using express.js. When I run the application on my laptop, on each request, I see a very large object dumped as JSON to the console. It starts like this and goes on for many lines:
{ domain: null,
_events: null,
_maxListeners: 10,
socket:
{ domain: null,
_events:
{ drain: [Function: ondrain],
timeout: [Object],
error: [Function],
close: [Object] },
_maxListeners: 10,
_handle:
{ writeQueueSize: 0,
owner: [Circular],
onread: [Function: onread] },
_pendingWriteReqs: 0,
_flags: 0,
_connectQueueSize: 0,
destroyed: false,
errorEmitted: false,
bytesRead: 483,
_bytesDispatched: 0,
allowHalfOpen: true,
writable: true,
readable: true,
server:
The odd thing is that the exact same code doesn't do this on my PC. I guess this isn't an error as such but it means I can't see any useful output in the terminal. I'm at a loss as to why I'm getting this output.

I resolved the problem by deleting the node_modules directory in my project and than running npm install to re-download the required modules. Clearly something wasn't right in one of the modules.

Related

Discord.js bot keeps getting random errors

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
});

Nodejs readline giving some error

I want to read a file line by line and based on the data in each line i have to categorise the data.
var rd = readline.createInterface({
input: fs.createReadStream('/home/user/Desktop/text.txt'),
output: process.stdout,
console: false
});
When this line is executed the file is read and printed in the terminal.
But when I try to read the file line by line using readline I am getting error.
rd.on('line', (input) => {
console.log(input);
});
I am getting the following error.
`Interface {
_sawReturnAt: 0,
isCompletionEnabled: true,
_sawKeyPress: false,
_previousKey:
{ sequence: '\n',
name: 'enter',
ctrl: false,
meta: false,
shift: false },
domain:
Domain {
domain: null,
_events: { error: [Function: debugDomainError] },
_eventsCount: 1,
_maxListeners: undefined,
members: [] },
_events: { line: [ [Function], [Function], [Function] ] },
_eventsCount: 1,
_maxListeners: undefined,
output:
WriteStream {
connecting: false,
_hadError: false,
_handle:
TTY {
bytesRead: 0,
_externalStream: {},
fd: 9,
writeQueueSize: 0,
owner: [Circular],
onread: [Function: onread] },
_parent: null,
_host: null,
_readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: [Object],
length: 0,
pipes: null,
pipesCount: 0,
flowing: null,
ended: false,
endEmitted: false,
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: null,
_events:
{ end: [Object],
finish: [Function: onSocketFinish],
_socketEnd: [Function: onSocketEnd],
resize: [Object] },
_eventsCount: 4,
_maxListeners: undefined,
_writableState:
WritableState {
objectMode: false,
highWaterMark: 16384,
needDrain: false,
ending: false,
ended: false,
finished: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: false,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 1,
prefinished: false,
errorEmitted: false,
bufferedRequestCount: 0,
corkedRequestsFree: [Object] },
writable: true,
allowHalfOpen: false,
destroyed: false,
_bytesDispatched: 22151,
_sockname: null,
_writev: null,
_pendingData: null,
_pendingEncoding: '',
server: null,
_server: null,
columns: 80,
rows: 24,
_type: 'tty',
fd: 1,
_isStdio: true,
destroySoon: [Function],
destroy: [Function] },
input:
ReadStream {
_readableState:
ReadableState {
objectMode: false,
highWaterMark: 65536,
buffer: [Object],
length: 0,
pipes: null,
pipesCount: 0,
flowing: false,
ended: true,
endEmitted: true,
reading: false,
sync: false,
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], data: [Function: onData] },
_eventsCount: 2,
_maxListeners: undefined,
path: '/home/user/Desktop/text.txt',
fd: null,
flags: 'r',
mode: 438,
start: undefined,
end: undefined,
autoClose: true,
pos: undefined,
bytesRead: 31,
destroyed: true,
closed: true },
historySize: 30,
crlfDelay: 100,
_prompt: '> ',
terminal: true,
line: '',
cursor: 0,
history: [ '1,2,3', '4,8,4,8', '2,2,2,2', '1,2,3,4' ],
historyIndex: -1,
prevRows: 0,
paused: true,
closed: true }`
Please help I am new to this.
Your code looks fine but you are using the Node.js REPL rather than running the code from a file, which is why you're seeing this behaviour.
The Node.js REPL (what you get when you type node in terminal) will store variables. However, when only an identifier is used the value is also returned. What you're seeing isn't an error, but the rd object.
The Node.js REPL is good for testing but, unless you have a specific reason for using it, the best thing to do is create an app.js file, add your code to it and then run node app.js.
If you do need to write multi-line code using REPL, then be sure to type .editor once initialised, so that whitespace, etc. is interpreted correctly.
Also, from the 7.7.2 docs console isn't an option which createInterface is expecting, so that can be removed. In your particular example, you could also remove output: process.stdout, as your logging each line using the line event

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.

WebSocket-node timeout parameter

I have implemented sockets using WebSocket-node package, now I am trying to set timeout so that if a socket is idle then it should get closed
While getting the detail of connection.socket
"console.log(connection.socket);"
I got below output
_events:
{ end: [ [Object], [Function] ],
finish: [Function: onSocketFinish],
_socketEnd: [Function: onSocketEnd],
drain: [ [Function: ondrain], [Function: socketOnDrain], [Function] ],
timeout: [Function],
error: [Function],
close: [Function],
pause: [Function],
resume: [Function],
data: [Function],
readable: [Function] },
_maxListeners: 10,
_writableState:
{ highWaterMark: 16384,
objectMode: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
sync: false,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
buffer: [] },
writable: true,
allowHalfOpen: true,
onend: null,
destroyed: false,
errorEmitted: false,
bytesRead: 950,
_bytesDispatched: 184,
_pendingData: null,
_pendingEncoding: '',
server:
{ domain: null,
_events:
{ request: [Function],
connection: [Function: connectionListener],
clientError: [Function],
upgrade: [Function] },
_maxListeners: 10,
_connections: 2,
connections: [Getter/Setter],
_handle:
{ fd: 11,
writeQueueSize: 0,
onconnection: [Function: onconnection],
owner: [Circular] },
_usingSlaves: false,
_slaves: [],
allowHalfOpen: true,
httpAllowHalfOpen: false,
timeout: 120000,
_connectionKey: '4:0.0.0.0:8000' },
As per the above output it seems timeout is set to 120000ms which means 2 mins but my socket is not getting close after 2 mins. Can you guys please help how to change this parameter and also to make sure connection gets close after that stipulated time.

Node.js spawn vlc child process not working in express

I'm using node.js and express to create a controller of sorts for my home media centre that can be operated through a browser.
I'm having a lot of trouble spawning the VLC process, but strangely only it works when executed from the node prompt, just not when run from file.
Here is what I have tested:
In the node command line/interpreter: require('child_process').spawn('vlc');
This works as I would expect, I can see the vlc window opens and persists on screen.
If I take the exact same line of code and I place it in another file (say test.js) and run that from the command line with node test.js nothing happens. Logging out the child process object a few seconds later gives me this:
{ _closesNeeded: 3,
_closesGot: 3,
signalCode: null,
exitCode: 1,
killed: false,
_internal: null,
pid: 11837,
stdin:
{ _handle: null,
_pendingWriteReqs: 0,
_flags: 0,
_connectQueueSize: 0,
destroyed: true,
bytesRead: 0,
bytesWritten: 0,
allowHalfOpen: undefined,
writable: false,
readable: false,
_connecting: false,
_connectQueue: null,
_idleNext: null,
_idlePrev: null },
stdout:
{ _handle: null,
_pendingWriteReqs: 0,
_flags: 1,
_connectQueueSize: 0,
destroyed: true,
bytesRead: 0,
bytesWritten: 0,
allowHalfOpen: undefined,
writable: false,
readable: false,
_events: { close: [Function] },
_connecting: false,
_connectQueue: null,
_idleNext: null,
_idlePrev: null },
stderr:
{ _handle: null,
_pendingWriteReqs: 0,
_flags: 1,
_connectQueueSize: 0,
destroyed: true,
bytesRead: 215,
bytesWritten: 0,
allowHalfOpen: undefined,
writable: false,
readable: false,
_events: { close: [Function] },
_connecting: false,
_connectQueue: null,
_idleNext: null,
_idlePrev: null } }
What is particularly weird about this is that I can launch other programs in the same way and it works. For instance replacing 'vlc' with 'gedit' results in the text editor appearing exactly as expected.
Anyone got ideas as to what this could be?
This is just a hunch, but I bet you are prematurely exiting your test before the VLC process even gets "running" so to speak.
Execute it like this:
var spawn = require('child_process').spawn;
var vlc = spawn('vlc');
vlc.on('exit', function(code){
console.log('Exit code: ' + code);
//EXIT TEST HERE
});
Spawn Documentation.
Edit:
Just saw 'test.js' and thought you were running a test. Post the relevant part of your Express code.

Resources