I am developing a small app in Node.js. I am just using Node.js for input and output. The actual website is just running through nginx. The website has a Websocket connection with node.js and is primarily used for db manipulations.
One of the things I am trying to do is get node to send small pieces of html along with the data from the database. I tried the following code.
simplified:
connection.on('message', function(message) {
fs.readFile(__dirname + '/views/user.html', function(err, html){
if(err){
console.log(err);
}else{
connection.sendUTF( JSON.stringify({
content: html,
data: {}
}));
}
});
}
});
When I console.log(html)
on the server or in the client I only get numbers back.
Anyone know what could be wrong.
NOTE: I really want to stay away from stuff like socket.io
, express
, etc. Just keeping it as simple as possible and no fallbacks are needed.
Using Clean architecture for Node.So far we sent html code directly from the send(0 function in response object. For sending larger code, we definitely require to have a separate file for html code. Response object gives a sendFile() function to return a html file to client.
If your node server also serves this HTML page, then you can use a relative path to point to your route like this: action="/handle-form-data" . The input tag nested inside the form is used to collect user input. You have to assign a name property to your data so that you can recognize this piece of data on the server.
If you don't specify an encoding for fs.readFile, you will retrieve the raw buffer instead of the expected file contents.
Try calling it this way:
fs.readFile(__dirname + '/views/user.html', 'utf8', function(err, html){
....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With