Use nodejs module in external javascript from the public folder - javascript

I included a module in my js file. Now i defined a button in a ejs file, which calls a function in an external js file from the public folder. How can i use the module in this function?
I tried to pass the module as a parameter, but i didn´t work. Is this even the right way to use this module in my external file?
the route js file
var express = require("express");
var router = express.Router();
var R = require("r-integration");
/* GET home page. */
router.get("/", function (req, res, next) {
res.render("Upload", { title: "Upload", para: R });
});
module.exports = router;
my ejs file with the button which calls the function loadScript()
Here i also tried to pass the paramter para to the const rModule
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<button onClick="loadScript()">Test Skript</button>
</body>
<script>
const rModule = para;
</script>
<script src="/javascripts/rScriptTest.js"></script>
</html>
the external js file from the public folder.
But here it says, that rModule is not defined.
function loadScript() {
let result = rModule.executeRScript("./RScripts/test.r");
console.log(result);
}

You can't pass a function though an EJS template. It won't serialize cleanly.
You need:
A JS script/module that will run on a browser
A URL for that file (usually provided with express.static)
You fail at the first hurdle. The module you are trying to use describes itself thus:
This is the R-integration API which allows you to execute arbitrary R commands or scripts directly from the node JS environment. This integration works on Windows and GNU/Linux based systems and uses system calls to access the R binary.
There is no way that it is going to achieve that without using Node.js-specific APIs that are not available in the browser.
You could write a web service in Node.js and interact with it using Ajax instead.

Related

How to use javascript methd from external files in hbs file

Let's say i have a simple project, index.html and one .js file with a method:
<!DOCTYPE html>
<html lang="pl">
<HEAD>
<script src="controller.js"></script>
<meta charset="utf-8"/>
<title>Project</title>
</HEAD>
<body>
<textarea id ="someID" name = "textFieldName"></textarea>
<button onclick="showNewData()">Button</button>
<p id="score"></p>
</body>
</html>
function getText(){
value = document.getElementById('someID').value;
}
function showNewData(){
getText();
document.getElementById('score').innerHTML = "Current data: "+value;
}
I tried to do the same on localhost:3000. So i've done npm project with express and hbs dependencies. It start from server.js file:
const express = require('express');
const port = 3000;
const app = express();
app.set('view engine', 'hbs');
app.get('/', (req, res) => {
res.render('index')
})
app.listen(port);
In "views" folder i have hbs file looked the same like former index.html file but it can't use javascript method from external file. Does anyone know how to do that?
in hbs file
As far as the browser knows, it is HTML. Clients do not care, and cannot know, if an HTTP response is generated by reading a static file or dynamically with some form of server side processing.
src="controller.js"
The value of the src attribute has to resolve to a URL containing the JavaScript
app.get('/', (req, res) => {
res.render('index')
})
The only URL your web server knows about (and so will provide anything other than a 404 error for) is /.
If you want /controller.js to provide a JS file then you need to write code to make that happen.
How to handle static files is covered in the Express Getting Started Guide.

Adding require keyword breaks vanilla JavaScript function

I have an HTML file as follows:
<body onload="myFunction('test');"
<div id="test"></div>
<script src="script.js"></script>
</body>
And the JS script is as follows:
function myFunction(id) {
const div = document.getElementById(id);
var html = "<p>test</p>";
div.innerHTML = html;
}
This works and the word "test" is displayed when I load my HTML file in my browser running http-server from npm
But when I add the following line with require for fs to my JS script, the function gives me the following error in VS Code: 'projectCarousel' is declared but its value is never read.ts(6133), and "test" ceases to get displayed when I load my HTML file in my browser:
const fs = require('fs');
Why is adding a line with require stopping my JS script from being executed when I load my HTML file in my browser?
Screenshots included below:
Before adding require
After adding require
You can't use require in the context of the browser, accessing the file system can only be done server side using node.js. Using express to serve your page could be an option.

How can I run a node.js file with a javascript command?

I am trying to make an online game. It is not fast-paced, so I only need a json file. I am very new to node.js and don't really know much about it.
I have tried using this: https://stackabuse.com/reading-and-writing-json-files-with-node-js/ and I understand how to read and write to it with the command line. How can I run a node js file from a javascript event like OnClick?
The node js:
//this code is mostly stolen from the site I linked to.
'use strict';
const fs = require('fs');
let newdata = {"newdata": "this is new!"}
let data = JSON.stringify(newdata);
fs.writeFileSync('data.json', data);
The json:
{
"test": "hello world"
}
The html:
<input type="button" value="Click Me!" onclick="
//run the node js file!!!
">
I have no idea what I can do to run the file.
I think before you solve this problem you need to ask yourself what you tried to get.
If you want to make a server which sends in REST API the JSON file, the idea to using NodeJS is a good way, but you need to let the web server to run in the background and use $.get commands at the HTML code to get the data.
If you want to read the JSON file locally you didn't need to use NodeJS (JS will be the good way to solve this)
For the first solution:
NodeJS code:
const data = require('/path/to/json/file/data.json')
var path = require('path');
const express = require('express')
const app = express()
app.get('/data', (req, res) => {
res.json(data)
})
app.get('/', function(req, res) {
res.sendFile(path.join('/path/to/index/file/index.html'));
});
app.listen('8080')
HTML code:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<body>
<button onclick="myFunction()">Test</button>
</body>
<script>
function myFunction(){
$.get("http://localhost:8080/data",
function(data) {
alert(JSON.stringify(data));
}
);
}
</script>
</html>

How to Access Local JavaScript File from a Cloud Functions HTML File?

I am trying to simply access a JavaScript file from within an HTML file using the script src attribute, and I have been unable to do so. Both files are in my functions folder.
I have the following Cloud Function index.js file in my functions folder:
const functions = require('firebase-functions');
const db = require('./admin');
var viewerApp = require('./viewerApp');
exports.view = functions.https.onRequest(viewerApp);
the viewApp.js file looks like this:
const express = require("express");
const fs = require('fs');
const viewerApp = express();
module.exports =
viewerApp.get('/:collection_name/:id', (req, res) =>
{
var viewerHTML = fs.readFileSync('./viewerApp.html').toString();
var id = req.params.id;
var collection_name = req.params.collection_name;
var rendered_HTML = eval(viewerHTML);
res.send(rendered_HTML);
}
)
You will notice the eval(viewerHTML) statement, which refers to a separate html file called viewerApp.html, which basically contains a template literal and looks like so:
<!DOCTYPE html>
<html lang="en">
<body>
...
</body>
</html>
(if someone has a better suggestion for separating the HTML into a separate file while being able to use ${variables} that would be helpful as well, as eval() is not ideal and perhaps is part of what is causing my problem)
The above works fine, except that I cannot figure out how to reference a JavaScript file located in the same functions folder, which means I would need to include all my JavaScript in the viewerApp.html file, which will be a mess.
I have tried all these possibilities in the viewerApp.html file (to try and refer to a JavaScript file called test.js):
<script src="./test.js"></script>
<script src="/test.js"></script>
<script src="test.js"></script>
<script src=test.js></script>
All of the above yield the following error in the console:
Uncaught SyntaxError: Unexpected token < test.js:2
(I get the same error if I try and refer to a filename that doesn't exist so I suspect a problem in the file path or limitation on the ability to access the local file system)
I don't know what to make of the error being related to a < character, as the content of test.js is simply:
console.log("logging happened");
Any assistance would be MUCH appreciated. Thank you!!
The problem in the end was that I did not initialize and configure firebase hosting which seems to be what allows html/js/css and other static files to be accessible in HTML returned from the cloud function. Once I did that and setup the public folder, I was able to refer to the test.js file by putting it in the public folder. That plus addition tweaks to the rewrite section of the firebase.json file, and I was all set. Following this video helped a lot and contains all the required steps.

Browser loading html in js file (node.js)

Apologies for the confusing title, the confusing title is a byproduct of my own confusion.
I am working with Node.js to write a web server and an api. Everything was going well, until I ran into this problem. Here is my server/api code:
const express = require('express');
const app = express();
const port = 9001;
const bodyParser = require('body-parser');
const mysql = require('mysql');
app.get('/profile/:url', (request, response) =>{
app.use('/profile/:url', express.static(__dirname+'/static_pages'));
response.sendFile('static_pages/test.html', {root: __dirname});
});
Here is test.html:
<!DOCTYPE html>
<html lang= "en">
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="./test.js"></script>
</head>
<body>
<div class="test">test</div>
</body>
</html>
here is test.js:
console.log('i run correctly!');
Now test.html does everything as expected if I open the file with a browser. However, if I run the server and navigate to 127.0.0.1:9001/profile/XXXXX , I get the following error:
Uncaught SyntaxError: Unexpected token <
Confused, I checked under "Sources" in Chrome devtools, and despite Chrome saying that it's loading "test.js" the code that it's running as "test.js" is identical to that of "test.html". Does anyone know why this is happening?
I used an identical method in order to deliver html/css/js in my other rest calls in the same file, and all of those pages are working as intended.
app.get('/profile/:url', (request, response) =>{
app.use('/profile/:url', express.static(__dirname+'/static_pages'));
response.sendFile('static_pages/test.html', {root: __dirname});
});
That doesn't make sense.
Every time you get a request for /profile/:url you try to set up the static plugin, then you return the contents of test.html.
When the browser asks for /profile/test.js that code … returns the contents of test.html.
Presumably you are planning to put some dynamic code in there to generate the profile page dynamically. That means you should not put the JS under `/profile/ because it isn't a profile page.
So:
Configure the static plugin properly:
app.get('/profile/:url', (request, response) =>{
response.sendFile('static_pages/test.html', {root: __dirname});
});
app.use(express.static(__dirname+'/static_pages'));
Point the URL at the right place:
<script src="/test.js"></script>
Note the . is removed so you are accessing from the root instead of from the current path segment.

Categories