Pass variable to html page with Nodejs

Asked

Viewed 4,927 times

2

Guys I made a list of files that exist in a certain folder, I would like after listing, It was possible to access this variable in HTML.

Server.js

var http = require('http');    
var arquivo = require('fs');
var server = http.createServer(function(request, response){      
    response.writeHead(200, {'Content-Type': 'text/html'});     
    arquivo.readFile(__dirname+'/pagina.html', 
        function(err, html){             
        if (err) {
            response.write("Arquivo não encontrado!");                   
            response.end();
        } else{
            response.write(html);   
            var fs = require('fs');
            var files = fs.readdirSync(__dirname+'/list/'); //VARIAVEL DA LISTA           
            response.end();

        }      
    });
});
server.listen(3000, function(){       
    console.log('Servidor está rodando!');     
});

html page.

<html>
<script type="text/javascript">
    alert(files); //Nome da variavel de lista do NODE
</script>
</hmtL>

1 answer

5

You cannot access a variable from an application server side written in Node at client side, directly in the browser. Although the programming language is the same, there are two runtimes totally different.

Anyway, there are several ways to achieve the result you want, which is to access a value generated on the server on the client side.

In PHP, it’s common to see things like <p>texto: <?php echo $var; ?> </p>. When the code is executed, the HTML is rendered with the contents of this variable and the end result is exactly what you look for (if you inspect the HTML in the browser, you will not see the tags PHP, only the final result). In the Node ecosystem this is possible using some kind of template engine such as, for example, the Jade. The reasoning is pretty much the same: you render the result on the server side, and send everything ready to the client side. In both examples, things live in separate places.

Another way to do this is to use asynchronous requests (AJAX) and the Express to the server. You instantiate a server already with predefined routes to access the values you want. See this reduced and functional example:

server.js

const http      = require('http');
const express   = require('express');
const path      = require('path'); 

const app = express();

let getData = () => {
    //O seu método de leitura do arquivo vem aqui
    return 'qualquer que seja o seu resultado aqui';
}

app.get('/data', (req, res) => {
    res.send(getData());
});

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname+'/index.html'));
});

http.createServer(app).listen(8080, () => {
    console.log('server funcionando');
});

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $.get('/data', function(res) {
                $('span').html(res);
            })
        });
    </script>
</head>
<body>
    <p>Minha data: <strong><span></span><strong></p>
</body>
</html>

Ensure that server.js and index.html are in the same folder, install the Express with $ npm i express --save, start the server with $ node server.js and see it working. I believe this is a first step towards achieving your goal.

EDIT 1

As pointed out in the comments, Jade is deprecated. Now called Pug

EDIT 2

It is implied by the question code that the work with the files will be synchronous. If it is not - as well pointed out in the comments - the flow will be different.

  • 1

    The Jade is depressed, is now called Pug. It should be noted that res.send(getData()); implies that getData() is synchronous, if there is no need to change i flow. +1

  • @Sergio I assumed that, in the OP method, he already uses synchronous readings, so I omitted the information. But if any way, I’ll edit the answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.