Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting node.js to read files in html format

Tags:

node.js

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.

like image 615
Saif Bechan Avatar asked Mar 17 '12 10:03

Saif Bechan


People also ask

Can we use html in node JS?

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.

How Pass value from node JS to html?

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.


1 Answers

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){
....
like image 88
Sebastian Stumpf Avatar answered Dec 03 '22 13:12

Sebastian Stumpf