L
L
lavagod2019-08-05 22:22:24
JavaScript
lavagod, 2019-08-05 22:22:24

How to include a javascript file in a NodeJS project?

Good afternoon.
I created calc.js with Jjon.js (parser generator) so got a compiler for the simplest calculator language. In order for the parser to work, you need to run the calc_run.js file in the terminal through NodeJS. The code for the example startup file calc_run.js is very simple, two lines. The code works (answer = 3) if you enter in the terminal: node calc_run.js

var parser = require('./calc.js');
console.log(parser.parse('1+2'));

And now I want to do the same, but through full-fledged NodeJS in the browser. I started a server.js file with settings
var http = require('http'),
    fs = require('fs');

fs.readFile('./calc.html', function (err, html) {
    if (err) {
        throw err; 
    }       
    http.createServer(function(request, response) {  
        response.writeHeader(200, {"Content-Type": "text/html"});  
        response.write(html);  
        response.end();  
    }).listen(8000);
});

i got a calc.html file with a simple structure
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>

  <h1>hello</h1>
  <!-- Как подключить скрипт calc_run.js? -->
    
</body>
</html>

The server starts on port 8000, hello is displayed, but I can’t connect the calc_run.js script. Even inserting the text of the calc.js + calc_run.js scripts into the calc.html document does not work. I really want the example to work not in the console, but on the server. As I understand it, inserting js code into an html document in NodeJS is somehow difficult, through paths, through creating variables for the server, and so on. But I can not find information about this (or I'm looking badly). Who will tell you how to insert calc_run.js into the calc.html document so that the example works and the parser gives a response from the working server under NodeJS?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey c0re, 2019-08-05
@erge

Scripts are inserted into HTML through the script
tag . But it will not be loaded, because your server can only serve one html page. look at the Express
framework

V
Vitaly, 2019-08-05
@vshvydky


, but through full-fledged NodeJS in the browser.
There are no nodes in the browser
Before practice, study the theory, otherwise it may be funny to others when they read the questions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question