How to send the data from the script to HTML page? - javascript

I am using Firebase to get the data
code:
const admin = require('firebase-admin');
const serviceAccount = require("C:/Users/santo/Downloads/bestmpos-firebase-adminsdk.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
let fs = admin.firestore();
let auth = admin.auth();
const listAllUsers = async (nextPageToken) => {
try {
let result = await auth.listUsers(100, nextPageToken);
result.users.forEach((userRecord) => {
start(userRecord.toJSON())
});
if (result.pageToken) {
listAllUsers(result.pageToken);
}
} catch(ex) {
console.log('Exception listing users:', ex.message);
}
}
async function first(){
await listAllUsers();
}
first();
async function start (object){
const info = await fs.collection('users').doc(object.uid).get();
if (!info.exists) {
console.log('No document');
} else {
console.table([info.data()]);
document.getElementById("greeting").innerHTML = info.data().toString();
}
}
HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="app3.js"></script>
</head>
<body>
<p id="greeting"></p>
</body>
</html>
but I want to send data console.log(info.data()) to HTML page to simply show information,
How can I do that, I don't want to use react or any other
can someone help me?
and I also is this Nodejs or plain javascript?

You can use innerHTML to sent data in your html.
Like this:
document.getElementById("yourElementId").innerHTML = info.data();
This is working for me:
<p id="greeting">
</p>
<script>
document.getElementById("greeting").innerHTML = "test"
</script>

Related

socket.io console.log(userName) not showing in the command line

I'm creating a chat application using socket.io, so basically what I'm trying is to console.log the user who joined the chat, here I'm taking a prompt from the client and emitting to the server, but cannot find any log in my command line. And on top I'm getting this error ERR_NAME_NOT_RESOLVED.
ERR_NAME_NOT_RESOLVED img
Index Html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>See-me</title>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script src="js/client.js"></script>
<link rel="stylesheet" href="css/styles.css">
<link rel = "icon" href ="logo/appIcon.ico" type = "image/x-icon">
</head>
<body>
</body>
</html>
Client Side Js:
const socket = io('http//localhost:3000')
const form = document.getElementById('send-container')
const messageInput = document.getElementById('messageImp')
const messageContainer = document.querySelector(".container")
const userName = prompt("Enter your Name to join");
socket.emit('new-user-joined', userName)
Server Side JS:
const io = require('socket.io')(3000)
const users = {};
io.on('connection', (socket) => {
socket.on('new-user-joined', userName =>{
console.log("New user", userName);
users[socket.id] = userName;
socket.broadcast.emit('user-joined', userName)
});
socket.on('send', message => {
socket.broadcast.emit('receive', {message: message, userName: users[socket.id]})
});
})
All I want is to console log the user who joined the chat.
The error is actually pointing to what the issue is:
const socket = io('http//localhost:3000')
That URL is missing a colon after http

Using fetch to read and write files

In my code i've a file called "orca.txt" it is just a number writen in this.
it looks like:
2300
I use fetch to read this number, i get it with:
fetch('orca.txt')
.then(response => response.text())
.then(textString => { contador=textString; });
It works very well, but then after i need to increase the value from the var contador,
so I use contador++; after i wanna to save this new value into the file "orca.txt"
i've tried this:
contador++;
var ct=contador.toString();
fetch("orca.txt",{method:'POST', body:ct})
.then (response => response.text());
but when i refresh the page or open in server the file orca.txt the value is same.
Can anyone help me how to write a value into a file (server file, no user file) using POST method?
Using PHP and file_put_contents and JS's Fetch API with FormData API
Create an index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DEMO</title>
</head>
<body>
<button id="increment" type="button">INCREMENT</button>
<input id="counter" type="text" readonly>
<script>
const EL_increment = document.querySelector("#increment");
const EL_counter = document.querySelector("#counter");
let counter = 0;
const incrementCounter = () => {
counter = parseInt(counter) + 1;
const FD = new FormData();
FD.append("counter", counter);
fetch("saveCounter.php", {
method: 'post',
body: FD
}).then(data => data.json()).then((res) => {
EL_counter.value = res.counter;
});
};
const init = async () => {
EL_increment.addEventListener("click", incrementCounter);
counter = await fetch('counter.txt').then(response => response.text());
EL_counter.value = counter;
};
init();
</script>
</body>
</html>
create counter.txt file:
2300
Create a saveCounter.php file:
<?php
$response = ["status" => "error"];
if (isset($_POST["counter"]) && file_put_contents("counter.txt", $_POST["counter"])) {
$response = ["status" => "success", "counter" => $_POST["counter"]];
}
echo json_encode($response);
exit;
Spin up your localhost server or for a quick test using cli-server run from terminal:
php -S localhost:8081
and head to http://localhost:8081 to try it out

How to handle an "undefined" error while converting CSV file to JSON using Papa Parse framework?

So, this is my JS code:
function main(){
let myJSON = parseCSV();
console.log(myJSON);
let myCSV = transformCSV(myJSON);
console.log(myCSV);
}
function parseCSV(){
let parsedJSON;
let selectedFile = document.getElementById('fileIn').files[0];
Papa.parse(selectedFile, {
complete: function(results) {
parsedJSON = results.data;
console.log(results.data);
console.log(typeof(results.data));
}
});
return parsedJSON;
}
function transformCSV(JSONIn){
let csvOut = ""; // i will do something here later
let dCol = ""; // i will do something here later
let dRow = ""; // i will do something here later
for (let i = 0; i < JSONIn.length - 1; i++) {
// i will do something here later
}
return csvOut;
}
And this is my test html page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src=".\transformCSV.js"></script>
<script src=".\node_modules\papaparse\papaparse.js"></script>
<input type="file" id="fileIn">
<input type="button" value="click!" onclick="main()">
</body>
</html>
When I try to read length of myJSON, I get error message in Chrome console: Uncaught TypeError: Cannot read property 'length' of undefined. Why is it undefined? It is present in console! Why does this happen and how to fix it? How to work with resulted myJSON as a perfectly normal static JSON?
You set the value of parsedJSON in the complete callback function. This will probably be called AFTER your function parseCSV has returned the undefined value of parsedJSON. You need to rewrite it with a callback or promise.
parseCSV(function (myJSON) {
console.log(myJSON);
let myCSV = transformCSV(myJSON);
console.log(myCSV);
});
function parseCSV(callback){
let parsedJSON;
let selectedFile = document.getElementById('fileIn').files[0];
Papa.parse(selectedFile, {
complete: function(results) {
parsedJSON = results.data;
callback(parsedJSON);
}
});
}

node.js server and .html file

I started to work with node.js two days ago. I made my http server with node.js and I have a page which I made few month ago for some test purposes, but when I host my page on my computer it it works but without javascript files which are included in html page, like jQuery and some graph lib.
I tried to debug it with IE debugger, but I cannot solve that.
Funny thing is that when I open same page from my disk, just double clicking on .html file, it runs fine without any errors!
My question is what I supposed to do to make work? Did I miss something with node.js?
I have one html5 canvas element on page, and maybe that is a problem
This is my index.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Hello Dialog</title>
<meta content="IE=edge" http-equiv="X-UA-Compatible">
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta http-equiv="Cache-Control" content="no-store">
<meta http-equiv="cache-control" content="max-age=0">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT">
<meta http-equiv="pragma" content="no-cache">
<link href="css/ui-lightness/jquery-ui-1.9.2.custom.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="RGraph.line.js"></script>
<script type="text/javascript" src="RGraph.common.core.js"></script>
<script type="text/javascript" src="RGraph.drawing.background.js"></script>
<script type="text/javascript" src="./js/jquery-1.8.3.js"></script>
<script type="text/javascript" src="./js/jquery-ui-1.9.2.custom.min.js"> </script>
<script type="text/javascript" src="index.js"></script>
<script type="text/javascript" src="temperature(1).json"></script>
</head>
<body style="font-size: 10px;">
<button id="btn_hello">Say Hello</button>
<button id="btn_hello1">LUKA</button>
<button id="btn_hello2">ANJA</button>
<button id="btn_hello3">MARKO</button>
<div id="dlg_hello">Hello World!</div>
<canvas id="graph" width="600" height="500"></canvas>
<script>
var data = [];
var limit;
var Temp = [];
var TimeStamp = [];
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
readTextFile("temperature(1).json", function(text){
data = JSON.parse(text);
for(var i =0; i<Object.keys(data).length; i++)
{
//alert(parseFloat(data[i].TimeStamp));
TimeStamp[i] = data[i].TimeStamp;
Temp[i] = parseFloat(data[i].Value);
}
DrawGraph(Temp, TimeStamp);
});
function DrawGraph(data, timestamp)
{
var line = new RGraph.Line({
id: 'graph',
data: data,
options: {
labels: timestamp,
gutterLeft: 55,
gutterRight: 35,
gutterBottom: 35,
gutterTop: 35,
title: 'A basic line chart',
backgroundGridColor: '#aaa',
backgroundGridDashed: true,
textAccessible: true,
scaleZerostart: true,
labelsOffsety: 5
}
}).draw();
}
</script>
</body>
</html>
and this is server.js in node.js
var http = require("http");
var fs = require("fs");
var windows1250 = require("windows-1250");
var ht = fs.readFileSync('./index.html',"utf-8");
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html','Content-Length':ht.length});
res.write(ht);
res.end();
console.log(req.url);
}).listen(8888, function () {console.log("server is listening on port 8888");});
The server does not know where to find your javascript files. You might want to look into using express.js. This provides the capability to use the express.static command.
You are not hosting the files. The server doesn't know where to look for the JavaScript files, so it simply doesn't include them.
Look into using serve-static or a better solution to vanilla HTTP servers, express.
There is another similar answer here.
I remember in nodejs, you can read html like this:
var fs = require('fs');
fs.readFile('/path/html', 'utf8', function (err, data) {
if (err) {
console.log(err);
} else {
res.send(data);
}
});
if you want a better location path of the file, you can use
var path = require('path');
path.join(__dirname, '/path/html');
Then it will be like this:
var fs = require('fs');
var path = require('path');
var file = path.join(__dirname, '/path/html');
fs.readFile(file, 'utf8', function (err, data) {
if (err) {
console.log(err);
} else {
res.send(data);
}
});

How to Have video recording and downloading using v2.2(version of opentok)

How to include video recording and downloading in this code, My previous query in this question was solved successfully but now I need to have archiving feature in this solution.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="myPublisherDiv"></div>
<div id="subscriberBucket"></div>
<script src="https://static.opentok.com/webrtc/v2.2/js/opentok.min.js" ></script>
<script type="text/javascript">
var apiKey = "<YOUR API KEY>";
var sessionId = "<YOUR SESSION ID>";
var token = "<YOUR SESSION ID'S TOKEN>";
session = OT.initSession(apiKey, sessionId);
session.connect(token, function (err) {
if (!err) {
session.publish("myPublisherDiv", { mirror: false });
}
});
session.on({
"streamCreated": function (event) {
session.subscribe(event.stream, "subscriberBucket", { width: 600, height: 450 }, { insertMode: "append" });
}
});
</script>
</body>
</html>
And please mention in yur answer if anything is wrong or not in this line
session.on({
"streamCreated": function (event) {
session.subscribe(event.stream, "subscriberBucket", { width: 600, height: 450 }, { insertMode: "append" });
I tested on another OpenTok app and clicked on mute and sound icons but could not reproduce what you are seeing.
I then created a new very simple group video chat app, clicked on mute and sound icons and I also could not reproduce what you are seeing.
I will paste in my group video chat app, you can start from this and slowly add in your own code part by part. Then you will be able to see what is causing your session to disconnect. Here is my simple group video chat app:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="myPublisherDiv"></div>
<div id="subscriberBucket"></div>
<script src="https://static.opentok.com/webrtc/v2.2/js/opentok.min.js" ></script>
<script type="text/javascript">
var apiKey = "<YOUR API KEY>";
var sessionId = "<YOUR SESSION ID>";
var token = "<YOUR SESSION ID'S TOKEN>";
session = OT.initSession(apiKey, sessionId);
session.connect(token, function(err){
if( !err ){
session.publish("myPublisherDiv");
}
});
session.on({
"streamCreated": function(event){
session.subscribe( event.stream, "subscriberBucket", {insertMode: "append"} );
}
});
</script>
</body>
</html>

Categories

Resources