2

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/'); //LIST FOLDER           
            response.end();

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

pagina.html

<html>
<script type="text/javascript">
    alert(files); //Name of var list
</script>
</hmtL>

2 Answers 2

1

Replacing a raw string with a variable has several clean solutions. I would recommend any of the following:

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

Comments

0

There are two ways to do this.

  1. separate your call into another endpoint on your server and make a request on the client (recommended since you will need this later probably)

  2. use regex to change your html file (fun experiment)

imagine your html file looks like this; notice the double brackets.

"<html><body><script> var files = {{myvars}} </script></body></html>"

and you have a list of files in an array

var yourFiles = ['file1', 'file2', 'file3']

you can then use regex to fill in the variables in the original html string

var newHTML = html.replace('/\{\{myvars\}\}/', JSON.stringify(yourFiles))
response.write(newHTML);
response.end();

the final html sent will look like this

"<html><body><script> var files = ['file1', 'file2', 'file3'] </script></body></html>"

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.