0

im beginner in Node.js and i have a problem... I dont know how send rows from server file to client file. example:

var app = require("http").createServer(handler)
var fs = require("fs");
var mysql = require('mysql');
var url = require('url');

app.listen(1337);

var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'wordpress1'
});

connection.connect();

connection.query("SELECT * FROM wp_comments", function(err, rows, fields) {
    rows[1].comment_author; // How send this to client file?
});

function handler(request, response) {
    var pathname = url.parse(request.url).pathname;
if(pathname === "/") {
fs.readFile('mysql.htm', function(err, content) {
    response.writeHead(200);
    response.end(content);
});
  }
}

and client file:

<!DOCTYPE html>
<html>
    <head>
    <title>dsfsd</title>
    <meta charset="UTF-8">
</head>
<body>
<script>
    // how to display a rows in this file?
    </script>
</body>
</html>

i heard something about common.js, require.js etc. but i dont know whether is this good way to build a node application?

1 Answer 1

2

First, because node is all non-blocking, you have to reorganize the app code like this:

function handler(request, response) {
    var pathname = url.parse(request.url).pathname;
    if(pathname === "/") {
        connection.query("SELECT * FROM wp_comments", function(err, rows, fields) {
            // AS JSON
            res.send(rows);
            // Alternatives:
            // SERVER-SIDE TEMPLATE
            // res.render('mysql.htm', {comment_author: rows[0].comment_author})
            // BASIC FILE 
            // res.sendfile('mysql.htm')  
        });
    }
 });

If you want to use a server-side template engine to render the html, I suggest jade. You could also receive the rows as JSON (which is how the above will actually send it as it stands) and then render it with a front-end templating engine, like AngularJS.

Sign up to request clarification or add additional context in comments.

Comments

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.