Sending text to the browser

I have managed to get file uploading work in Node.js with Express, and in the code i'm checking whether it's an image or not that the user is trying to upload.

If the file was successfully uploaded I want to show a message to the user, directly to the HTML page with the uploading form. The same should be if the file the user tried to upload wasn't an image, or something else happened during the upload.

The code below works (res.send...) but it opens up a new page containing only the message.

My question is: How can I change my code so that the message is sent directly to the HTML page instead? If it could be of any use, i'm using Jade.

Thanks in advance!

app.post('/file-upload', function(req, res, next) {
    var fileType = req.files.thumbnail.type;
    var divided = fileType.split("/");
    var theType = divided[0];

    if (theType === "image"){
        var tmp_path = req.files.thumbnail.path;

        var target_path = './public/images/' + req.files.thumbnail.name;

        fs.rename(tmp_path, target_path, function(err) {
            if (err) throw err;

            fs.unlink(tmp_path, function() {
                if (err) {
                    throw err;
                    res.send('Something happened while trying to upload, try again!');
                }
                res.send('File uploaded to: ' + target_path + ' - ' + req.files.thumbnail.size + ' bytes');
            });
        });
    }

    else {
        res.send('No image!');
    }

});

from what I understand you are trying to send a message to an already open browser window?

a few things you can do,

  1. Ajax it, send the post, and process the return info.
  2. Submit it as you are doing now, but set a flash message (look at http://github.com/visionmedia/express-messages) and either res.render the form page, or res.redirect to the form function
  3. now.js or a similar solution. This would let clientside use serverside functions and serverside code to run clientside functions. So what you would do would be on submit, pass the post values to a serverside function, which will process it and trigger a clientside function (display a message)

For my money option #2 is probably the safest bet, as clients without javascript enabled will be able to use it. As for usability #1 or #3 would give a more streamlined appearance to the end user.

You can use WebSockets. I recommend using Socket.IO, it's very easy to work with. On the client-side you would have an event-handler which would use JavaScript to append the new information to that page.

You could then have the server for example say:

socket.emit('error', "Something happened while trying to upload, try again!");

and the client would use:

socket.on('error', function(data){
  //alert?
  alert(data);
});

http://socket.io/#how-to-use