Pass variable to html page with NodeJS

0

I made a listing of files that exist in a particular folder, I would like that after listing, it would be 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!');     
});

page.html

<html>
<script type="text/javascript">
    alert(files); //Nome da variavel de lista do NODE
</script>
</hmtL>
    
asked by anonymous 18.04.2017 / 18:37

1 answer

1

You can not access a variable from a server side application written in Node on the client side , directly in the browser window. Although the programming language is the same, they are two entirely different runtimes .

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

In PHP, you often 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 final result is exactly what you are looking for (if you inspect the HTML in the browser, you will not see the tags the end result). In the Node ecosystem this is possible using some kind of template engine such as Jade . The rationale is pretty much the same: you render the server-side result, and send everything ready to the client side. In both instances, things live in separate places.

Another way to do this is to use asynchronous requests (AJAX) and Express for the server. You instantiate a server already with predefined routes to access the values you want. Here is a small, 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>Minhadata:<strong><span></span><strong></p></body></html>

Makesureserver.jsandindex.htmlareinthesamefolder,installExpresswith$npmiexpress--save,starttheserverwith$nodeserver.jsandseeitworking.Ibelievethisisafirststeptowardsachievingyourgoal.

EDIT1

Aspointedoutinthecomments,Jadeisdeprecated.Nowit'scalled Pug

EDIT 2

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

    
18.04.2017 / 20:17