Is there a way to get new Data on HTML without restarting the server? - html

I have a problem with my node.js express Server. I got an audio file. Every 5 seconds my raspberry pi records another audio file with the same name. This audio file should run on my website. My website refreshes every 10sec, but the audio file which is played stays the same. How can I have the latest Audiofile played?
Here's my HTML:
e meta http-equiv="refresh" content="10"/> !-- Refreshes every 10 seconds -->
/head> body background="bg.png" >
<audio autoplay><source src="Aufnahme.wav" type="audio/wav"/></audio>
</body>
</html>
(I know I don't have some "<" but it appears to not work here and I don't know the Escape signs)
And this is my Node.js Code, I'm also using express.
var res = require('http');
var express = require('express');
var app = express();
var fs = require('fs');
app.use(express.static('www'));
var server = app.listen(8000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Express app listening at http:\/\/%s:%s', host, port);
});
I think it is something about my Nodejs, can someone help me pls? Or didn't I grasp some concept of Server/Client?
Sorry I'm new to this

Maybe your audio file is in browser cache...
So one idea is to simulate a versionning of your audio file...
For exemple in your code, genere a new Id call 'myNewId'.
In you html
<audio autoplay><source src="Aufnahme.wav?${YOU PUT YOU NEW ID HERE DEPENDING YOUR TEMPLATE ENGINE}" type="audio/wav"/></audio>

Related

How can you send an html page with an image from a file via node.js

I am trying to send an html page with express from the node.js server but for some reason I cannot add an image that is a file
This is the code I tried:
const express = require("express");
const app = express();
app.use((req, res) => {
res.send(`<body><img src='test.png'></body>`)
});
Would appreciate help.
where should the code must look for the image?
it needs the relation address of the image in src property.
ex: '../../resources/img/test.png'

Prefetch script from server (not from cache) for next time

If browser has a cached version of a JS file, I want it to be loaded and executed.
I also want this cache to be refreshed with a fresh copy from the server after each execution.
<script src="script.js"></script> <!-- cache-control: private, max-age=86400 -->
script.js
var prefechscript = document.createElement('link');
prefechscript.href = 'script.js';
prefechscript.rel = 'prefetch';
prefechscript.as = 'script';
document.head.appendChild(prefechscript);
But this method does not work because the browser prefetch from cache.
Would you have a way to achieve this?
I wish <link> has an attribute fetch-from-server, so it will always pull a copy from server and store it in cache if server respond with a cache-control.
I am looking to have a solution at least for Chrome.
Edit:
In my case, the URL of the script tag <script src="script.js"></script> cannot be changed.
If you change the URL of a resource that was cached you will receive a new version. A simple way is to use the current time to do this:
const prefetchscript = document.createElement('link');
prefetchscript.href = 'script.js';
prefetchscript.rel = 'prefetch';
prefetchscript.as = 'script';
document.head.appendChild(prefetchscript);
window.setTimeout( ()=>{ let now = new Date(); prefetchscript.href = 'script.js?t='+ now.getTime(); } );

How to link Node.js Post script to HTML form?

I have created a REST full APi, which works as I would be expecting if I am running Postman. I run the Test from an index.js file which would have the routes saved as per below file.
const config = require('config');
const mongoose = require('mongoose');
const users = require('./routes/users');
const auth = require('./routes/auth');
const express = require('express');
const app = express();
//mongoose.set();
if (!config.get('jwtPrivateKey'))
{
console.log('Fatal ERRORR: jwtPrivateKey key is not defined')
process.exit(1);
}
mongoose.connect(uri ,{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
})
.then(()=>console.log('Connected to MongoDB...'))
.catch(err=> console.log('Not Connected, bad ;(', err));
app.use(express.json());
//THis is only for posting the user, e.g. Registering them
app.use('/api/users', users);
app.use('/api/auth', auth);
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
The real code is happening here. Testing this in Postmon I could establish, that the values are saved in MongoDB.
router.post('/', async (req, res) => {
//validates the request.
const { error } = validate(req.body);
if (error) return res.status(400).send(error.details[0].message);
let user = await User.findOne({email: req.body.email});
if (user) return res.status(400).send('User Already Register, try again!');
user = new User(_.pick(req.body, ['firstName','lastName','email','password','subscription']));
const salt = await bcrypt.genSaltSync(15);
user.password = await bcrypt.hash(user.password, salt);
//Here the user is being saved in the Database.
await user.save();
//const token = user.generateAuthToken();
//const token = jwt.sign({_id: user._id}, config.get('jwtPrivateKey'));
const token = user.generateAuthToken();
//We are sending the authentication in the header, and the infromation back to client
res.header('x-auth-token',token).send( _.pick(user, ['_id','firstName','lastName','email','subscription']));
});
Now my question's are:
How can I call the second code block from a , in one particular html file. When using Action="path to the users.js", the browser opens the js file code but doesn't do anything.
Do I need to rewrite the Post block part so that it would as well include the connection details to the DB? And would this mean I would keep open the connection to MongoDB once I insert Read etc.? Wouldn't this eat a lot of resources if multiple users would e.g. log in at the same time?
Or is there a way how I can use the index.js + the users.js which is refereed in the index.js file together?
All of these are theoretical questions, as I am not quite sure how to use the created API in html, then I created as walking through a tutorial.
Do I need to change the approach here?
After some longs hours I finally understood my own issue and question.
What I wanted to achieve is from an HTML page post data in MongoDB through API (this I assume is the best way how to describe this).
In order to do this I needed to:
Start server for the API function e.g. nodemon index.js, which has the information regarding the API.
Opened VS Code opened the terminal and started the API server (if I can call it like that)
Opened CMD and startet the local host for the index.html with navigating to it's folder and then writting http-server now I could access this on http://127.0.0.1:8080.
For the register.html in the form I needed to post:
This is the part which I didn't understood, but now it makes sense. Basically I start the server API seperatly and once it is started I can use e.g. Postmon and other apps which can access this link. I somehow thought html needs some more direct calls.
So After the localhost is started then the register.html will know where to post it via API.
Now I have a JOI validate issue, though on a different more simple case this worked, so I just need to fix the code there.
Thank You For reading through and Apologize if was not clear, still learning the terminology!

Nodejs Express not loading script files

I am trying to run a angular app thru node-express.
1 File Structure
AngularNode
public
/core.js
/index.html
project.json
server.js
2 server.js
var express = require('express');
var app = express();
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
// listen (start app with node server.js) ======================================
app.listen(8000);
console.log("App listening on port 8000");
3 index.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="./core.js"></script>
........
4 core.js
angular.module('MySystem',[])
.controller('AppController',['$scope',function($scope){
$scope.Name ="Testing Text";
}]);
When I tried to run this app using node server.js this, index.html file is getting loaded properly, however this is not detecting or loading core.js file. and I am getting following errors
Uncaught SyntaxError: Unexpected token < core.js:1
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.4.5/$injector/modulerr?p0=MySystem&p1=Error%3…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.4.5%2Fangular.min.js%3A19%3A381) angular.js:38
Now, when I open index.html file directly from explorer, this is working OR when same code I move from core.js to inline html, under <head> with <script> block it is working.
I am not sure, why core.js not detecting or loading when I run thru node.
Got the Solution with few modifications:
1 Added line in server.js
app.use(express.static(__dirname + '/public')); after line
var app = express();
2 Case correction(Capital 'f') for function from res.sendfile('./public/index.html'); to res.sendFile('./public/index.html');
Now I can see core.js is detected and working fine.
The app.get('*', function(req, res) { is a catch all rule for all get request and will also match the ./core.js request. So for the ./core.js your express app will also send the html file.
You should use express.static instead:
var express = require('express');
var app = express();
app.use(express.static('./public'));

Nodejs + Firefox behavior in relation to the HTML5 <audio> element

I am using Nodejs and Firefox to display a web page. That page has a HTML5 audio element. The problem I have is related to the calcul of the audio duration.
In my node js script I have:
var app = require('http').createServer(handler)
, path = require("path")
, io = require('socket.io').listen(app)
, fs = require('fs')
, exec = require('child_process').exec
, spawn = require ('child_process').spawn
, util = require('util')
, extensions = {
".html": "text/html",
".css": "text/css",
".js": "application/javascript",
".png": "image/png",
".gif": "image/gif",
".ttf": "application/x-font-ttf",
".jpg": "image/jpeg",
".mp3": "audio/mp3",
".wav": "audio/wav",
".ogg": "audio/ogg"
}
, Files = {};
In my html web page I have:
<audio id="idaudio" src="" type="audio/wav" >Your browser does not support the audio element.</audio>
And some javascript code from my web page:
var thissound=document.getElementById("idaudio");
thissound.src="http://localhost/Audio/Song.wav";
//thissound.src="/Audio/Song.wav";
thissound.addEventListener('loadeddata', function() {
var durationaudio = (thissound.duration)*1000;
});
When I check the durationaudio I get the right number and then I can play the song using thissound.play(); This code is working in Firefox and Chromium.
If I change
thissound.src="http://localhost/Audio/Song.wav" -> thissound.src="/Audio/Song.wav"
Adding the ".wav": "audio/wav" extension in the node script, I can play the Song using Firefox and Chromium; In Chromium I get also the right number of the durationaudio but using Firefox I get a durationaudio=Infinity. This is the problem. I dont know why Firefox is not able to get the right duration. Maybe I have to add some extension ... in the node script in order to allow Firefox to get the duration of the audio. Any ideas?