20

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.

2
  • Step 3 of this? Also, apparently you might want to replace "sendHeader" with "writeHead". Commented Mar 17, 2012 at 10:16
  • Where do I replace senHeader? Commented Mar 17, 2012 at 10:53

1 Answer 1

48

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){
....
Sign up to request clarification or add additional context in comments.

1 Comment

Ok, I will try that. I thought I read in documentation that it automatically defaults to utf8 when you do not specify any. Maybe I overlooked something. Will try this and report back.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.