How to view [Circular] in Node? - node.js

In my console, I'm getting:
{
'a': [Circular],
'b': [Circular],
'c': [Circular]
}
How can I see the contents of [Circular]? I've tried console.log(), util.inspect() and console.dir() and I'm still getting [Circular] instead of the actual content.
Edit:
I'm trying to see the actual content, how many layers deep it goes, etc., for debugging purposes. Linked question does not address any of that.

Basically that's recursion, as far as I know there is no way to possibly log a [Circular] reference (don't quote me on that), but if you could it would probably be like this:
{
'a': {
'a': {
'a':{
// never ending
}
}
}
}

Related

How do I get the internal id of a Node Timeout using the symbol without hardcoding a lookup index?

When you create a timer in Node, you get the following object back:
Timeout {
_called: false,
_idleTimeout: 500,
_idlePrev: [TimersList],
_idleNext: [TimersList],
_idleStart: 34,
_onTimeout: [Function],
_timerArgs: undefined,
_repeat: null,
_destroyed: false,
[Symbol(unrefed)]: false,
[Symbol(asyncId)]: 5,
[Symbol(triggerId)]: 1 }
The actual numeric id of this timeout object is contained under the [Symbol(asyncId)] field. My problem is, how can I get a reference to this symbol in a non-hackish way? The only way I currently know of that will give me this object is Object.getOwnPropertySymbols(), but using a hardcoded index seems fragile as f:
$ node -p 't=setTimeout(()=>{}, 500); triggerSym=Object.getOwnPropertySymbols(t)[2];t[asyncId]'
67
Is there a less fragile way I can get a reference to this symbol to use for lookup?
You can absolutely use Object.getOwnPropertySymbols to list the symbols of the timer object and then iterate to find the one you want. In my opinion that is pretty ugly and basically the same as relying on an implementation detail or using a _foo private-ish property on an object.
Currently the main case I know of for public symbol usage in Node is with promisifyable functions, where users can use
const promisifySymbol = Symbol.for('nodejs.util.promisify.custom');
The Node timer docs have no mention of such symbols, so I would recommend not using these symbols.
If you do need the ID itself to handle serialization of the timer's info or something, the timer [Symbol.toPrimitive]() implementation returns the ID directly, or indirectly, e.g.
const timer = setTimeout(() => {}, 0);
console.log(timer[Symbol.toPrimitive]()); // explicit call
console.log(+timer); // implicit call

Why is the JSON output different from the actual output as rendered in the browser? [duplicate]

I have a problem with logging out the contents of an array inside an object. The actual object looks like this
var stuff = { accepted: [ 'item1', 'item2' ],
rejected: [],
response: 'Foo',
envelope: { from: 'The sender', to: ['new item1', 'new item2'] },
messageId: 'xxxxxxxxxxxxx' } }
The console.log shows the items of the first array fine but the second array is being output as [Object].
{ accepted: [ 'item1', 'item2' ],
rejected: [],
response: 'Foo',
envelope: { from: 'The sender', to: [Object] },
messageId: 'xxxxxxxxxxxxx' } }
What is happening here and how can I get the items of the second array to show when I console.log. Thanks for any help!
UPDATE
Sorry, I forgot to add that I am working exclusively in Node.js so it's a server side log that needs to display the object exactly as it's received from a callback with a straight console.log, ie. no further stringify-ing.
I also just tried creating another random object with a similar structure like this.
var objText = {
fun: {
stuff: 'Some stuff',
list: ['this', 'it', 'takes']
}
};
The console.log for the above is:
{ fun: { stuff: 'Some stuff', list: [ 'this', 'it', 'takes' ] } }
This appears to be the same structure to me and yet the console.log works fine so it seems to be perfectly possible in Node to log arrays content even when it's embedded inside and an object inside an outer object.
It looks like this is an old topic, anyway
I've faced the same issue, embedded array printed as [Array].
It is because of console.log in the node.js uses util.inspect for print, the default depth is 2.
So, to print something which is deeper than 2 followings can be used:
const util = require('util')
console.log(util.inspect(errors, true, 10))
This is the default way for some browser and implementations of showing too complex or deep objects/arrays with console.log. An alternative is to use JSON.stringify with console.log:
var stuff = {
accepted: ['item1', 'item2'],
rejected: [],
response: 'Foo',
envelope: {
from: 'The sender',
to: ['new item1', 'new item2']
},
messageId: 'xxxxxxxxxxxxx'
}
console.log(JSON.stringify(stuff, null, 4));
EDIT:
Another alternative is to use console.dir in case you have a too complex or recursive object, see https://stackoverflow.com/a/27534731/6051261
Try it with: console.log(JSON.stringify(variable))
If you like Chrome devtools, that folds your json objects and let you observe a lot of things, you can use the --inspect flag:
node --inspect index.js
The console will then give you an URL and you just have to copy paste in Google Chrome to enjoy Google Chrome console.
More information on this link

node-github: "getStatsContributors" doesn't return results properly

This is how I'm using the method:
github.repos.getStatsContributors({
repo: 'Cloudformation-Webserver',
owner : 'DorrinPk'
}, function (err, res) {
console.log(err, res);
});
The first time I run it for the repo I get null results. The second time I run it I get :
null { data: [ { total: 4, weeks: [Object], author: [Object] } ], meta: { 'x-ratelimit-limit': '5000',
'x-ratelimit-remaining': '4968',
'x-ratelimit-reset': '1499712495',
'x-oauth-scopes': 'admin:org, admin:repo_hook, notifications, repo, user',
'x-github-request-id': 'A05B:0684:271B6:59CB1:5963C4D0',
'x-github-media-type': 'github.v3; format=json',
etag: '"f1ea81d88281adf31e1178d0804f230c"',
status: '200 OK' } }
I know total:4 is the number of my commits on the repo but I only get [Object] back for author and weeks.
am I doing something wrong? I was expecting to get similar results to this.
The first thing you are printing out to the console is the err object from the response. In this case the request was successful, so the error is null.
The second thing you are writing is the response object. When using the console.log method like that it will not display all levels deep of an object and you must either use the inspector to get a better look or write out the property itself (in your case you could use console.log(res.data[0].author))
You are getting the correct results, it is just that the console.log method is printing out differently than what you were expecting to see, but it is all there.

How do I query a complex key in pouchDB?

If I was to make a get request, I'd do something like:
https://myserver.com/sometestdb/_design/sortJob/_view/index?limit=100&reduce=false&startkey=["job_price"]&endkey=["job_price", {}]
For a map query like:
function(doc) {
if (doc.data.type === "job") {
emit(["job_ref", doc.data.ref], null);
emit(["job_price", doc.data.price], null);
}
}
How would I replicate the query using pouchDb query? I've tried a few things around the start and end keys but no luck:
{
include_docs: true,
startkey: 'job_price',
endkey: 'job_price,{}'
}
{
include_docs: true,
startkey: 'job_price',
endkey: 'job_price\uffff'
}
Both of these return 0 results whereas the link I use produces the expected results.
Note: I can confirm the data is present in my pouchDB as I've queried it using the pouch-find plugin but am trying various techniques to see which is faster.
EDIT: According to the complex keys section in the docs, I should be able to do the following:
{
include_docs: true,
startkey: '[\'job_price\']',
endkey: '[\'job_price\',{}]'
}
But that results in:
No rows can match your key range, reverse your start_key and end_key
or set {descending : true}
But I should be able to get results like this and don't want descending: true.
Ok, so it was my reading of the documentation that was off.
When building the start / end key, you need to pass the array, not pass the array as a string (which I thought pouchDB then eval'd.
This is the working query:
{
include_docs: true,
startkey: ['job_price'],
endkey: ['job_price', {}]
}
Posting this answer rather than deleting the question as it might help someone else.

NodeJS and MongoDB update not working

I have this loop in a Node and Mongo application. console.log will output all the 'product' names correctly, however, rank is usually not set correctly in the database. Interestingly enough, if I put a debug breakpoint in the program and step through slowly, it works. Any idea if there is some sort of race condition taking place, and what the best solution for making this work would be?
async.each(sortedProductsArray, function (product, callback) {
console.log(product.name);
var query = {
productNo: product.productNo
};
var index = sortedProductsArray.indexOf(product)+1;
var update = {
// give it a rank
$set: { 'rank': index }
};
// main products array
products.update(query, update, callback);
});
you should probably be using forEachOf and this will return the index as the second parameter, e.g.:
async.forEachOf(['a', 'b', 'c'], function () {console.log(arguments)});
{ '0': 'a', '1': 0, '2': [Function] }
{ '0': 'b', '1': 1, '2': [Function] }
{ '0': 'c', '1': 2, '2': [Function] }
and then you should be using this index rather than doing another search over your products collection
edit:
when you call products.update(query, update, callback); this affects the products array, and therefore may not be valid when you do your indexOf() (may not exist) which is why the rank sometimes isnt populated

Resources