1

I have the route /test:

app.route('/test', (req,res)=>{
    res.sendFile(__dirname + "\\myhtml.html")
})

And I need to have node fire an event on my /test route, and the myhtml.html file can listen for that event, retrieve the data sent through when the server fires it. My example (not real) code is:

page = app.route('/test', (req,res)=>{
    res.sendFile(__dirname + "\\myhtml.html")
})

page.fire('mything',{one:2})

And then in myhtml.html,

idk_express_parent_thing.on('mything', (res)=>{console.log(res)})

Without socket io, should be native express, js, idk.

sld
  • 93
  • 10

3 Answers3

2

I'm not sure if this may be able to help you, but I'm going to try.

I thought about three possible solutions...:

  1. Maybe, socketing may be a solution in your case, using Socket.IO, or something. In this case, the back-end would send the file to the client, which when rendered would connect to the server and listen for something, maybe using some id. I just think that maybe it would bring too much complexity, but... it's maybe a solution...

  2. Another one, probably more suitable, can be that you store the message that you need to be sent, somewhere (I recommend Redis, or you can try using it in server memory) and then, after the server sends the file to the client, the client makes a request to the server, asking for that message by sending the Redis key used to identify the stored message

  3. A last one, is maybe using cookies, session and related... Where, you would simply save the message into cookies/session, along with the file, then, the file would have access to the data when on the client

I also did some research, and I found this StackOverflow anwnser (the second answer is going to maybe help you, the first one talks about EJS and other engines... which you said you can't use)

Hope it helps! ;D

  • Thanks! This is really useful, just one thing, how would I make an event to wait for those that my html file can listen for - can you provide some code? – sld Sep 05 '21 at 06:25
  • So, in this case, I imagine your going with the socket solution... Firstly I recommend you use socket.io as it is the most known and also what I know about the most... So after instaling, importing, and setting it all up (both on the client and server-side), you need to create on both ends functions that will create the socket/connection (this will make the file listen for server messages, and also the as well as in the opposite direction too. Then you should be able to make the server emit a message to all clients or, to just one client... – Victor Gomez Sep 05 '21 at 06:41
  • thanks, but I have since edited my question. try to read it again – sld Sep 05 '21 at 06:42
  • Here are some links that may help: Installation + setup: https://socket.io/docs/v4/server-installation/ Server-side broadcasting + connection: https://socket.io/docs/v4/broadcasting-events/#To-all-connected-clients-excepting-the-sender Client-side socket connection + listening; https://socket.io/docs/v4/client-socket-instance/ And here an example I found of a chat react app that may be helpful for you to understand: https://dev.to/safak/react-instant-chat-app-using-node-js-and-socket-io-5c7k – Victor Gomez Sep 05 '21 at 06:43
  • Yes, I read it again already. I was just taking some time to write down the links with code on a second comment as there is the characters limit... I hope those links help, it's pretty much all the code you need to send a basic message to connected clients or to just one client – Victor Gomez Sep 05 '21 at 06:45
  • thanks. I am trying to make my own socketio kinda thing though. – sld Sep 05 '21 at 07:27
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/236785/discussion-between-sld-and-victor-gomez). – sld Sep 05 '21 at 18:14
0

you have to set route correctly. if you have myhtml.html file in root direcotry app.route('/test', (req,res)=>{ res.sendFile(__dirname + "/myhtml.html") })

it will be work

  • thanks, except I am on windows, so I use \\ instead of /, and this does not answer my question about sending messages. – sld Sep 05 '21 at 05:56
0

So I am answering my own question because I found out about js WebSockets, and the WebSocket-Node lib - they allow full-duplex communication beetween server, and client, and are simple to use. here is server code:

const nwss = require('websocket').server;
const http = require("http");

var server = http.createServer(function(request, response) {
    console.log(' Received request for ' + request.url);
    response.write("example")
    response.end();
});

server.listen(8000, ()=>{console.log("ready")})

ws = new nwss({
    httpServer: server,
    autoAcceptConnections: false
})
ws.on('request', (req)=>{
    let conn = req.accept('example-protocol', req.origin);
    console.log('accepted ' + conn.remoteAddress)
    conn.on('message', (msg)=>{
        if (msg.type == 'utf8') {
            console.log('Recieved utf8 ' + msg.utf8Data);
            conn.sendUTF(`thanks for "${msg.utf8Data}"`)
        }
    })
    conn.on('close', ()=>{
        console.log(`${conn.remoteAddress} disconnected.`)
    })
})

(it is a bad idea to allow other sites to connect, so use an if statement to check if the origin is ws://yoursiteurl/) And client:

let socket_url = "ws://" + new URL(location.href).host + "/"
let WSocket = window['MozWebSocket'] ? MozWebSocket : WebSocket;
let socket_ = new WSocket(socket_url, 'example-protocol') //the example-protocol is the same i put in the server code, as it has to be.
function start() {
    socket_.onmessage = (msg)=>{
        console.log(msg.data)
    }
    socket_.send("hi, do you read? :P")
}
//call start once it connects.
sld
  • 93
  • 10