0

I have created a little web app on my own server. It contains only a few html, css and javascript files. I want to put a node.js with a simple code:

var mysql = require('mysql');
var fs = require('fs');
var con = mysql.createConnection({
  host: "example",
  user: "example",
  password: "example",
  database: "example"
});
con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
con.query("SELECT *example", function(error, data, fields) {
  if (error) throw error;
  const jsonData = JSON.parse(JSON.stringify(data));
  console.log("jsonData", jsonData);
  });
});

The question is how to execute node.js on a server? I want to do it with a javascript so lets suppose I want to write an execution between <script> tags. Is it possible?

3
  • 1
    Your question is rather unclear. As you asking how to run a completely separate program with Node.js from another program already running in Node.js? Are you asking how to program with Node.js from another program running from a <script> element in a browser? Commented Sep 28, 2020 at 12:13
  • The same way you do with PHP or Ruby or Java - just run your program in the command line. And the same with PHP or Python or C++ you cannot put node.js code inside script tags. Also the same way with Java or Python or Perl, to communicate with node.js you use regular HTTP requests using regular mechanisms such as forms or AJAX (XMLHttpRequest or the more modern fetch) Commented Sep 28, 2020 at 22:43
  • I was just wondering if there is any alternative way to do that. I think I get it now. Thanks a lot! Commented Sep 28, 2020 at 22:52

1 Answer 1

1

I want to do it with a javascript so lets suppose I want to write an execution between <script> tags. How to do it?

You don't, per se.

Putting JS code in a script element in an HTML document and then giving it to a browser to run is one way to execute JS.

Putting JS in a file and running it with Node.js is a different way to run JS (and one which gives access to a different set of APIs, which is why JS running in Node.js can directly access a database but JS in a browser can't).


To trigger the execution of JS with Node.js from a browser you would typically:

  • Wrap the JS function you want to execute in Node.js in a web service (typically using the Express.js module)
  • Use Node.js to run that web service application (typically using PM2 to monitor it and restart it if it falls over)
  • Have a seperate JS program run in the browser and use Ajax to make an HTTP request to that web server.
Sign up to request clarification or add additional context in comments.

1 Comment

Hi there, so should he just perform a GET query? I'm just curious.

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.