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>
Related
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.
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.
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.
I have a text file that I would like to read with Node.js using the fs module. I know how to read the file but I do not know how to take the data of the text files and be able to put it to a website page.
For Example: I would like to read a file that has the contents of 'hello world!!!' and then using jQuery put it to a div.
NodeJS is not a web server.
However, you can easily add dependencies to provide such
capabilities.
e.g. express, koa, or hapi.
So far, you've got [something like]:
const fs = require('fs');
fs.readFile('data.json', (e, data) => {
if (e) throw e;
console.log(data);
});
You could use express as follows (note: if you have not
already run npm init, do so and provide sensible defaults):
npm init
npm install --save express
Then, create a file, app.js, to serve you're data, e.g.:
const fs = require('fs');
const express = require('express');
const app = express();
app.use('/', (req, res) => {
if (e) throw e;
// **modify your existing code here**
fs.readFile('data.json', (e, data) => {
if (e) throw e;
res.send(data);
});
});
app.listen(5555);
Launch your node "web server":
node app.js
Finally, point your browser to:
http://localhost:5555/
If you are using jquery and express just build an endpoint on your express server that serves the contents of the text file.
your jquery:
$.getJSON("/text", function(data){
<write code here to render contents of text file to the DOM>
})
your end point in node:
router.get("/text", function(req, res){
fs.readFile(textFile, 'utf8', function(err, data) {
if (err) throw err;
return res.json(textFile);
})
})
})
As I understand your question you want to "render" the text on the client, not on the server. The easiest way to do this with jQuery is using $.ajax like this:
const URL_TO_STATIC_TXT = 'https://cdn.rawgit.com/fabe/2a371ce28effb32fa1120f8d25225d37/raw/6d0bfebff1d0b52d72ed5ded4011a0bbff80d679/file.txt';
$.ajax({ url: URL_TO_STATIC_TXT })
.done(data => {
$('body').text(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Then you only need to host the static .txt files with Node.js, without even using fs. With Express you can achieve this with app.use:
app.use('/', express.static(__dirname + '/public'));
If you want to render the files on the server (using fs) you can also look into countless templating libraries like pug.
I don't know what is the purpose of this, but you can use Express to start a simple web server that provide the content of your text file. Then, you just need to request this web server from your website page using jQuery.
const URL_TO_STATIC_TXT = 'https://cdn.rawgit.com/fabe/2a371ce28effb32fa1120f8d25225d37/raw/6d0bfebff1d0b52d72ed5ded4011a0bbff80d679/file.txt';
$.ajax({ url: URL_TO_STATIC_TXT })
.done(data => {
$('body').text(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
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.