How to retrieve logged data from the browser console to http server - javascript

I want to use node.js to creat http server that listen to a port 3000 for example. on another port 8000 I am running a javascript for video playing. I am log some data while the vide is playing with console.log but I can not save the logged data to a file directly.I thought of using the http server to do that. But I do not know how to create the post requests from the client to the server.
Can you please help..
Thanks in advance

You can replace the default console.log function with a custom function that make a post request every time you log something.
let originalConsoleLog = console.log;
console.log = function (...args) {
postLog(args); // Send logs to the server
originalConsoleLog.apply(console, args); // Call the original console.log function
}
where the postLog function will send the data to the nodejs and can be something like
function postLog(args) {
var newXHR = new XMLHttpRequest();
newXHR.addEventListener( 'load', reqListener );
newXHR.open( 'POST', '/saveLog' );
var jsonData = { logs: args };
var formattedJsonData = JSON.stringify( jsonData );
newXHR.send( formattedJsonData );
}
postLog function based on this gist

Related

How to connect to a TCP server and pass a Javascript to it

I'm definitely a newbie with JS and node. I have telescope management software called SkyX Pro, and it has the ability to run a TCP Server on port 3040. I can connect to it using Netcat and hand it a Javascript starting with //* Javascript *// this works and allows me to startup cameras and other equipment and send commands for taking pictures etc. The issue is it needs to be run from a batch file which makes getting any information back to an HTML page tough (Like Camera, focuser and filter wheel status and temperatures).
The NC call looks like "NC localhost 3040 < Javascript-file.js
To get around the browser to local machine security issues I want to run this from node.js with maybe socket.io-client if possible, but I don't know the proper syntax for it.
I have seen plenty of client syntax sending hello's etc. but nothing send javascript and allowing for two-way connectivity that I can understand.
I have tried using:
var socket = io.connect('http://localhost');`enter code here`
socket.on('httpServer', function (data) {
console.log(data);
document.write(data + "\r\n");
socket.emit('tcp', "For TCP");
});
const net = require('net');
const client = new net.Socket();
client.connect({ port: 3040, host: process.argv[2] });
client.on('data', (data) => {
console.log(data.toString('utf-8'));
But I do not understand it well enough to troubleshoot why it's not working.
Any help would be wonderful, and please treat me like a baby that needs its step by step.
Cheer
Peter
Reading [1], We can assume socket-io isn't the perfect fit for you, because that Server you have sound like a typical tcp-socket server, not a socket.io server ( which requires special headers ) or a web-socket server.
So you only needs "net" library to do the job.
const net = require('net');
// module to send a message to TCP-socket server and wait for the response from socket-server
const sendAndReceive = async (client, message) => {
client.write(message);
let response = null
await ( new Promise( (resolve, reject) => {
client.on('data', function(data) {
response = data;
resolve()
});
}))
return response;
}
// send a single message to the socket-server and print the response
const sendJSCode = (message) => {
// create socket-client
const client = new net.Socket();
client.connect(3040, 'localhost', async function() {
console.log('Connected');
// send message and receive response
const response = await sendAndReceive(client, message)
// parse and print repsonse string
const stringifiedResponse = Buffer.from(response).toString()
console.log('from server: ', stringifiedResponse)
// clean up connection
client.destroy()
});
}
sendJSCode('var Out; \n Out="TheSky Build=" + Application.build \n\r')
This script will:
Initiate a socket client
on connection successfully, client sends a message
client receives back response from that message
client prints response to terminal
Note that TheSkyX has a limitation of 4096 bytes for each message[2], any more than that and we will need to chunk the message. So you may want to keep the js-code short and precise.
that snippet I gave is minimal, it doesn't handle errors from server. If you want, you can add client.on("error", .. ) to handle it.
Your point of connecting to the socket server directly from browser is very intriguing, unfortunately it is not allowed by modern browsers natively due to security concerns 3
[1] https://socket.io/docs/#What-Socket-IO-is-not:~:text=That%20is%20why%20a%20WebSocket%20client,to%20a%20plain%20WebSocket%20server%20either.
[2] https://www.bisque.com/wp-content/scripttheskyx/scriptOverSocket.html#MSearchField:~:text=set%20to%204096%20bytes

How to constantly update and push data with WebSocket?

I have a ws.js which is my server:
// A simple server-side script.
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ port: 3000 });
let number = 0.0;
function updateNumber(){
number = Math.random().toFixed(4);
}
// Desperetly tried this.
var emitter = function() {}
var emission = function(data) {
emitter(data);
}
// Then my WebSocket stuff.
wss.on('connection', function(ws) {
emitter = function(data) {
wss.clients.forEach(function(client) {
// ---> How to constantly run updateNumber()
// As long as connection is live.
console.log(data);
// Debug
console.log('[server:onConnect] Received request.');
// Send the transmission.
console.log('[server:onConnection] Sending:', number);
client.send(number);
});
}
});
I have to do this without using setInterval() as the number will be coming from a file that is constantly being updated.
So in my server's verbosity stream, in the terminal I get this, once the client connects in:
[server:onConnection] Sending: 0.9569
[server:onConnect] Received request.
[server:onConnection] Sending: 0.4058
[server:onConnect] Received request.
[server:onConnection] Sending: 0.7813
[server:onConnect] Received request.
[server:onConnection] Sending: 0.9672
[server:onConnect] Received request.
[server:onConnection] Sending: 0.0671
[server:onConnect] Received request.
[server:onConnection] Sending: 0.5682
[server:onConnect] Received request.
[server:onConnection] Sending: 0.0171
--- UPDATE ---
The problem is fixed when I tweaked the updateNumber() function as:
function updateNumber(){
number = Math.random().toFixed(4);
emission();
}
This seems to be successfully bridging the emitter function burred inside the on connect block and the updateNumber() function.
However, this solution still requires a setInterval() to run the updateNumber() in order to create the emission of a constantly changing number. Is there a way to create a function that runs and constantly emits a random number, without using setInterval().
https://www.linode.com/docs/development/introduction-to-websockets/
This article can help you to understand websocket correctly and how you can listen functions without setInterval

How do I successfully console log the data from this api?

When I go into the Network tab and inside response, I do get the results of this API, but I cannot get it to output in the console.
This is the code:
const NAMEURL = "https://uzby.com/api.php"
// get data from api
function getDataFromApi(value, callback){
const QUERY = {
min:`${value}`,
max:`${value}`
}
$.getJSON(NAMEURL, QUERY, callback)
}
function renderResult(result){
return `${result}`;
}
// render results to page
function displayName(data){
console.log(data);
const results = renderResult(data);
$('.nameResult').html(results);
}
// wait for user to submit
function watchSubmit() {
$('.js-search-form').submit(event => {
event.preventDefault();
const queryTarget = $(event.currentTarget).find('#js-dropValue');
const thisquery = queryTarget.val();
getDataFromApi(thisquery, displayName);
});
}
// running the watch submit function waiting for click
$(watchSubmit);
I tried doing a console.log(getDataFromApi()) but I get undefined in console.
console.log(getDataFromApi()); would never work, its displayName() that you would have to console log.
Your code was not wrong, with the exception of what you were trying to console log, but even then its not going to work because uzby does not want to share its resources directly with your application.
So indeed that error you were getting, the CORS error is the problem.
You need to proxy that request through your own server, the one that loads your page. You will have to research documentation on your server side language proxy. A potential solution for your code could be like this:
xmlhttp.open(
'GET',
'https://cors-anywhere.herokuapp.com/https://example.com/api.php?' + param,
true
);

Cannot Send Function In Object Javascript Using Socket IO

This Is my code client socket.io, im trying to emit data and callback to server
_this.emitHandler = function(event, data, callback){
var packet = {};
if(data){
packet.data = data;
}
if(callback){
packet.callback = callback;
}
io.emit(event, packet); // emit packet to server with data and callback
}
and when i console.log my packet its just print data, the callback disappeared. this is my server code
io.on('*', function(socket, args, next){
console.log(args) // this args just print data in console
}
im using socket.io-event btw to capture all event, is something wrong with my code?
You can't send function like that.
What you can do is to JSON.stringify it and on the server call eval() on it.
Remember that it's dangerous. Anybody could send some code to your server and execute it.

How to get response from node-xmpp request?

I learned to make request with the XMPPserver by using node-xmpp library. Now i can make the request as mentioned in XMPP extensions documentations. But now i want to get the callback response for the each request (especially the XML response).
Here i have used the following code the make a request subscription (friend request) to a another user
var net = require("net");
var xmpp = require('node-xmpp');
var cl = new xmpp.Client({ jid: "one#localhost", password: "comet123$" })
cl.addListener('online', function(data) {
console.log('Connected as ' + data.jid.user + '#' + data.jid.domain + '/' + data.jid.resource)
//making subscription
var stanza = new xmpp.Element('presence',{
to: "hai#localhost",
from: "one#localhost",
type: "subscribe",
}).up
// making request
cl.send(stanza);
// nodejs has nothing left to do and will exit
cl.end()
})
I want to know, how to get the response result.
I tried with the callback functionality with as llike this,
cl.send(stanza, function(result){
console.log(result);
});
and also like this
var result = cl.send(stanza);
This returns only true,
So can anyone please tell me how do I get the callback result for the requests that we make by using the node-xmpp libarary
There is no callback or return for XMPP messages. You will have to have to set up an event listener to pick up messages coming back from the server. Add:
cl.on('stanza', function(stanza){
// Do something with the stanza
// If you want to end after the first message you get back, move this here
cl.end();
});
you can get raw data from connection
cl.connection.on("data", function (data) {
console.log('data', data.toString('utf8'));
});

Categories

Resources