how to get rid of method names when console.log a function? - javascript

something like this in the output:
{
array x [a,b,c,d]
],
method: [Function: method],
method2: [Function: method2],
method3: [Function: method3]
}
PS: this is the output not my code itself. It's just better to highlight it as code snipped
i just want to log the function without all that additional text for the methods.
I'm using VS Code + Node JS

Related

Javascript Object returns empty when called

a piece of my code
const channels = fauna.paginate(q.Match(q.Index("channels"), "true")) // Query FaunaDB database for channel list => create constant called users containing results
const channelList = channels.each(function (page) {
// Logs the page's contents,
// for example: [ Ref(Collection("test"), "1234"), ... ]
console.log(page);
});
works fine and behaves how it supposed to. however, when I try to call "channelList" from elsewhere in my code it returns {}
The console.log in the first piece of code returns what it is supposed to as well so I dont think there is anything wrong with the first chunk of code.
Here is a piece of code where I attempt to call this object
let options = {
options: {
debug: config.twitchConfig.options.debug
},
connection: {
reconnect: config.twitchConfig.options.reconnect,
secure: config.twitchConfig.options.secure
},
identity: {
username: config.twitchConfig.connection.username,
password: config.twitchConfig.connection.password
},
channels: [JSON.stringify(channelList)] // Attempt to call here, Returns {} (Empty object)
};
Is there something I'm missing? is this even possible in the first place? if its not possible whats another method i can use to achieve the same result?
Edit: From what I can gather, channelList is based off of the page response, and it seems like the page response is private to that function and cannot be referenced outside of the function. what can I do to either make it referencable outside of the function or create a constant/variable that can be accessed outside of the function containing the same information
channelList is not a function, more like it is the result of a function that prints the channels.. so after printing what is assigned to it is the result..
Try assuming it as a function and then invoking it:
const channelList = ()=>{
channels.each(function (page) {
// Logs the page's contents,
// for example: [ Ref(Collection("test"), "1234"), ... ]
console.log(page);
});
};
channelList();
Assuming the code itself does what you want it to, this should do the job
After much trial and error my answer was way simpler than me or anyone else I have spoken to thought.
Here's a step by step guide on how to fix the problem yourself if you're experiencing the same issue as I was.
Use a variable instead of a constant
declare your variable before setting it by placing var channelList; somewhere above your code that sets it
set the previously declared variable with a simple channelList = page
console.log(channelList); just to make sure its all working
Finally, call the variable where you want it, and voila! you have your variable properly called and it doesn't return {} or Undefined or [Object Object]

Is there a way to work-around site(s) breaking console.log

Excerpt of my Chrome DevTools Console:
Navigated to https://twitter.com/
console.log.toString();
"function (){}"
Navigated to http://linuxfr.org/
console.log.toString();
"function log() { [native code] }"
I managed to inject code in the main frame of twitter.com, using a Chrome Extension, but I had a hard time understanding why my code seemed to not run. It appears that my code is running fine, except console.log produces exactly nothing!
Question: is there a way to call the "now gone" console.log "native code"?
(remarks about that kind of JavaScript "WAT" behavior retracted, sort of)
As this is a Chrome Extension, you set your content script to run_at: "document_start" - you can(theoretically) "grab" console.log / error / dir / info etc before twitter gets it's grubby hands on them
actually, KNOWING that twitter only replaces log, warn, info, error, you can simply do:
var _console = ['log', 'warn', 'info', 'error'].reduce(function(result, key) {
result[key] = console[key].bind(console);
return result
}, {});
then you can use _console.log and friends
As far as I know, it depends on how deep replacement was done.
For example if it was like this
console.log = function () {};
The original native log function is still in prototype. You can access it using __proto__ property or Object.getPrototypeOf method.
console.log = null
Object.getPrototypeOf(console).log
//log() { [native code] }
Also you can just delete replacement from original console object
delete console.log
//true
console.log
//log() { [native code] }
But all above code won't work if I replace log function like this
console.__proto__.__proto__.log = function () {}
And unfortunately I don't know workaround for this case.
Based on the discussion above and #JaromandaX and JavaScript: The Definitive Guide below is one simple polyfill.
function log() {
if (location.hostname === 'twitter.com'){
Object.getPrototypeOf(console).log.apply(console, arguments);
} else {
console.log.apply(console, arguments);
}
}

Get HTML Source of WebElement in Selenium WebDriverJS

There is a similar question out there (an older one in Python) but this one has to do with JS. Testing using Selenium in a NodeJS, Mocha environment. What I'd like to do is click on a Bootstrap dropdown and check the HTML to look for changes. I've tried the following:
test.it('should click on all header links',
function() {
var elem = driver.findElement(By.id('Profile'));
console.log(elem.getAttribute('innerHTML'));
console.log(elem.getInnerHtml());
});
Both calls return the same thing.
{ then: [Function: then],
cancel: [Function: cancel],
isPending: [Function: isPending] }
I plan to feed the HTML into cheerio so i can check for structure changes. Appreciate any help on this.
I was able to retrieve the HTML as a string by doing the following.
driver.findElement(By.id('Profile')).getAttribute("innerHTML").then(function(profile) {
console.log(profile);
});
I got the inner HTML with:
element.getAttribute('innerHTML').then(function (html) {
console.log(html)
})

Retrieving a List of network interfaces in node.js (ioctl SIOCGIFCONF)

I'm new to node and am hacking together a node application utilizing node_pcap to capture packet data and do interesting things with it. One of the inputs to capturing data is the network interface to listen on, i.e. "eth0".
I thought it would be really great if I could programmatically look up the available interfaces on the system and present them to the user of the program and allow them to pick which interface to listen on. In C, I would use ioctl (or ioctlsocket with winsock) using SIOCGIFCONF.
My question is, does there currently exist a mechanism to do this in node? I've searched quite a bit and haven't arrived to any such solution.
If this functionality does not currently exist, I would assume I'd be able to write a Module binding in C/C++ using ioctl to accomplish this.
Thank you for your time!
Update valid as of Node 13.7.0
This has been renamed since this answer was submitted. It is now just networkInterfaces() like this:
require('os').networkInterfaces()
Or probably preferably like this:
import { networkInterfaces } from 'os';
const interfaces = networkInterfaces();
New docs url: https://nodejs.org/docs/latest/api/os.html#os_os_networkinterfaces
Original answer
As of Node.js 0.6.0 you have
require('os').getNetworkInterfaces()
See http://nodejs.org/docs/latest/api/os.html#os.getNetworkInterfaces
If you want to list only the name of interfaces :
Object.keys(os.getNetworkInterfaces())
// [ 'lo0', 'en0', 'en3', 'awdl0' ]
os.networkInterfaces() method returns an object containing only network interfaces that have been assigned a network addresS but if we want all network card in machine we can use this method
var shell = require('shelljs');
var interfaceCard = shell.ls('/sys/class/net');
this interfaceCard has list of all network interfaces
output will be
[ 'eth0',
'eth1',
'lo',
stdout: 'eth0\neth1\nlo\n',
stderr: null,
code: 0,
cat: [Function: bound ],
exec: [Function: bound ],
grep: [Function: bound ],
head: [Function: bound ],
sed: [Function: bound ],
sort: [Function: bound ],
tail: [Function: bound ],
to: [Function: bound ],
toEnd: [Function: bound ],
uniq: [Function: bound ] ]
interfaceCard=interfaceCard.stdout.split('\n');
interfaceCard = eth0, eth1, lo

Purpose of this javascript, what kind of design patten it used?

if (!window['console']) {
window.console = {
log: function(msg) {}
}
}
$(window).ready(function() {
Site.onReady();
});
var Site = {
host: null,
path: null,
etc..
And there have var Helpers, var Site, looks pretty good, but can't understand the purpose? Anyone who knows that?
if (!window['console']) {
window.console = {
log: function(msg) {}
}
}
This checks to see if there's anything currently assigned to window.console already and if there's not, it assigns a custom object that has a 'log' function. This makes window.console.log usable no matter what, and if there's already a native (or earlier defined) version of the function, it will be used.
$(window).ready(function() {
Site.onReady();
});
var Site = {
host: null,
path: null,
etc..
I have no idea what this is for, but Site is undefined at the time it is placed into the anonymous callback for $(window).ready(), which is something that should be avoided (just place the $(window).ready() below where site is defined)
As for this specific snippet:
$(window).ready(function() {
Site.onReady();
});
this passes an anonymous function to the $(window).ready() function, which will call it when the DOM is ready. Using an anonymous function directly avoids the need to name a function and then pass it in later.
function myFunc() { //we can use myFunc anywhere now, which may be unwanted
Site.onReady();
}
$(window).ready(myFunc);
Lastly:
var Site = {
host: null,
path: null,
etc..
The var myVar = {key1:"value", key2:"other_value"}; syntax creates a new object with keys and values that can be used like this: myVar.key1 = "newValue!"
Looks like it initializes several global objects that are expected on the page. For example console, which is available in Firefox/Firebug for logging, but not other browsers. So by checking for existence of window['console'] and adding it when necessary, you can trust in the JavaScript code you can call console.log() without causing an error.
I assume Site, Helpers, etc all do something similar.
its defining a 'console' object literal on the window object, if it is not already there, which has a function log. This means in your code you can write
console.log('something')
even if the browser doesn't support it.

Categories