Is it possible to add Node script data to html?

Asked

Viewed 973 times

0

I am quite beginner under the Node.js, but wanted in humility to understand why a code only appear on the console.log of Node and not be able to store in some variable so that I can manipulate it in html with raw javascript, since only if I open an html file with imported Node, the console says the command require was not defined.

This is the API I’m using: https://github.com/matheuss/google-translate-api

    var http = require('http');

    const translate = require('google-translate-api');

    var server = http.createServer(function(req, res) {

    var url = req.url;


    translate('We did it!', {to: 'pt'}).then(res => {
      console.log(res.text);
    //=> I speak English
    console.log(res.from.language.iso);
    //=> nl



    }).catch(err => {
     console.error(err);
    });



    });

     server.listen(1337, '127.0.0.1');

     console.log('Server running at http://127.0.0.1:1337/');

However, I’m lost on how to use html :( Please someone help me or give me some alternative that can use pls.

  • 1

    Vixi... difficult to understand your question. Node runs in the back end the script is executed and stored in memory, the HTML javascript runs in the front end (in the client/browser). Some Node libraries (modules) can be run on the front end natively or with the use of Browserify as long as they are designed to do so or perform functions and resources supported by both environments. You want to pass a javascript object from Node to front-end?

  • 1

    The function "require()" is one of the Node import (Loader) methods, where the script searches (imports) libraries or even other scripts (not necessarily "modules"). Newer versions of Node as well as modules that follow a newer pattern use "import". You can take the call from your js by route, modify it (since it is only text) and return a custom script, there are pros and cons in this "method". I would recommend that you edit up your question. Not clear enough to submit an answer.

  • Like, the most direct question would be... You could use some Node.js data on an html page (clientside), or in no way ? Because I only want this data that the object has, that would be a string containing a translation...

  • You can fetch this data using REST making a request with AJAX or Fetch ... you can use JSON.stringy() to turn this data into a {String} and accommodate your HTML to return to the user and search in DOM this data simply making JSON.parse() or you can modify your javascript to return this data. There are several ways, you should only think of the "less expensive" and that meets your needs. How do you think it should be?

  • How do you "fuel" the translate function with a {String}? Is sending this {String} via POST to the server? If this is the case, this is REST...just return the result. That’s what you’re looking for?

  • When a request is made to the server it can return only one response at a time. It is not possible to return multiple responses, only the first one is sent and closes the connection. So either you use REST to search the translation for a "request path" or parse in your "document" to add this information to the document or you can parse in your javascript file to return this object on itself js and use it on the front end.

  • Possibly related: https://answall.com/questions/269121/cant-set-headers-after-they-are-sent-express-js/269134#269134

  • Lauro, thank you so much for your patience. It’s... I just really wanted to do it in the simplest way. For example, I’m not even doing it professionally, it was a test (I’m quite a beginner with Node.js), then what I really wanted was "only" take the data of a given object and show it in html, by test. Like, this my code that I made available in the question was made with the intention of just testing, if you see, the input is default: Translate('We Did it!', {to: 'pt'}), what I wanted was to store this output data in a variable and somehow send in html...

  • I wanted to do it as simply as, for example: "<p><? php $varContendoSaidaTraduzida ? > </p>"... What I want to do is so simple, but as I don’t have as much knowledge with Node.js is becoming a headache.(And it has nothing to do with php, just said more or less my intention)

Show 4 more comments

1 answer

2


As already mentioned, Node runs server-side, so it will not run inside a client-side html. Think that the Node variables are in a separate context from the javascript that will run on the front. As already said, you would have to make a request to your server to fetch the data from the Node side. Or also, inject the variables into the HTML and then send them to the client.

Thinking about your comment about wanting to use as "<p><?php $varContendoSaidaTraduzida ?> </p>"..., I think the closest that would be to using a Template Engine.

The template engine will allow you to enter chunks of code in the middle of your HTML. For example, using EJS:

<body>
  <h1> Hello world! <%= message %> </h1>
</body>

Based on what you already have, I’ll give you an example using template engine and also calling Node(server) with Fetch. It’s quite simple, actually. The first step for you, would be to listen for the requests and return an html:

var http = require('http');
const translate = require('google-translate-api');
var server = http.createServer(function(req, res) {
     var url = req.url;
     //Escutando em localhost:1337/translate
     if(url ==='/translate'){
         translate('We did it!', {to: 'pt'}).then(response => {
             var translated = response.text;
             res.write('<h1>'+translated+'<h1>');
             res.end(); //end the response
         }).catch(err => {
             console.error(err);
         });
     }else{
         res.write('<h1>Not found!<h1>');
         res.end(); //end the response
     }
});
server.listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

This will cause you to see the translated message when accessing the localhost:1337/Translate browser.

Now what we need to do is install the template engine and create an HTML to render as soon as we receive a request, and then send it back.

First, install the EJS: npm install ejs

Now create a file called home.ejs on the same level as your app.js (or the name you gave to your Node server), with the following code:

<head>
  <meta charset="UTF-8">
</head>
<body>
  <h1> Tradutor </h1>
  <p> <%= message %> </p>
  <p> <%= translation %> </p>
  <p id='test'></p>
</body>
<script>
  //chamada para /fetchdata do client-side para o server-side
  fetch('/fetchdata').then(response => {
    return response.json();
  }).then(data => {
    document.getElementById('test').innerHTML = data.example;
  }).catch(err => {
    console.log(err);
  });
</script>

Now, finally, change your app.js to the following one:

var http = require('http');
var ejs = require('ejs');
var fs = require('fs');

const translate = require('google-translate-api');
var server = http.createServer(function(req, res) {

    var url = req.url;

    //chamada para root
    if(url ==='/'){
      res.write('<h1>Welcome!</h1>');
      res.end();
    }
    //chamada para /translate
    else if(url ==='/translate'){
       translate('We did it!', {to: 'pt'}).then(response => {
           var translated = response.text;
           //ler o arquivo home.ejs
           var html = fs.readFileSync(__dirname + '/home.ejs', 'utf8');
           //json para injetar na view
           var json = {
             message: 'Olá!',
             translation: translated
           }
           //injetar json e rendizar com ejs (template engine)
           var htmlRenderizado = ejs.render(html, json);
           //envia para o client
           res.write(htmlRenderizado);
           res.end();
         }).catch(err => {
           console.error(err);
         });
     }
     //chamada para /fetchdata
     else if(url === '/fetchdata'){
       var data = {
         example: 'Data from fetch!'
       }
       res.writeHead(200, { 'Content-Type': 'application/json' });
       res.write(JSON.stringify(data));
       res.end();
     }
     else{
        res.write('<h1>Not found!<h1>'); //write a response
        res.end(); //end the response
     }
});
server.listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

Now you have an example of how to use a Template Engine and also how to request an html for Node! I strongly advise to take a look at Expressjs, it will greatly facilitate the use of routes (which in this example is well simplified).

Browser other questions tagged

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