Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting Node.js script to a front-end project

As a javascript newbie, I want to create a front-end project with a very little backend solution using Node.js.

I have a user inteface with some variables and a button. These variables have to be passed to a simple .txt file(on my filesystem) and overwrite its content. For this, I'm using a nodejs script:

var fs = require('fs');

fs.writeFile('log.txt', 'This is my text', function (err) {
  if (err) throw err;
  console.log('Replaced!');
});

But I want this to work onClick, whereas this only works from the command-line.

So I have the two following problems:

  1. I want to update the .txt file with the button click. So basically the above written code has to be executed, when I click the button. But I don't understand, how to connect the front-end with this nodejs file.
  2. I want the content to be dynamical. I'm sure, once the first problem is solved, this will be straightforward, but right now I don't know this either.

I'm 100% sure I'm missing something(maybe a web-server, but even then, how?). I did my research but all I found was either an overkill or I didn't even understand it. Any help would be appreciated, a tutorial, an advice or just a keyword, that I can use for my research.

like image 338
hotigeftas Avatar asked Mar 07 '23 22:03

hotigeftas


1 Answers

Have a look at express. It's a "Fast, unopinionated, minimalist web framework for node". With this you can build a small webserver:

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World');
});

app.listen(3000); // Webserver is running on port 3000

If you run it and got to your browser on http://localhost:3000, it would print Hello World.

Now what you would do is calling your logging function every time a specific URL is requested.

var fs = require('fs');

function log(text, callback) {
  fs.writeFile('log.txt', text, callback);
}

app.get('/', function (req, res) {
  log('This is my text', function (err) {
    if (err) throw err;
    res.send('Replaced!');
  });
});

Now when you click the button you need to make an AJAX request to the server (maybe using jQuery).

like image 110
mbrandau Avatar answered Mar 16 '23 21:03

mbrandau