ExperimentalWarning: Conditional exports is an experimental feature" - node.js

I am getting this in error in node js while running a server. The error is as follows
"(node:17160) ExperimentalWarning: Conditional exports is an
experimental feature". This feature could change at any time"?
Full details can be found here
Any idea how to solve this? I am getting it in the terminal while running the nomemon server.js. My codes are as follows:
Here is mine:
Server.js
const express = require('express')
const app = express()
const server = require('http').Server(app)
const io = require('socket.io')(server)
const { v4: uuidV4 } = require('uuid')
app.set('view engine', 'ejs')
app.use(express.static('public'))
app.get('/', (req, res) => {
res.redirect(`/${uuidV4()}`)
})
app.get('/:room', (req, res) => {
res.render('room', { roomId: req.params.room })
})
io.on('connection', socket => {
socket.on('join-room', (roomId, userId) => {
socket.join(roomId)
socket.to(roomId).broadcast.emit('user-connected', userId)
socket.on('disconnect', () => {
socket.to(roomId).broadcast.emit('user-disconnected', userId)
})
})
})
server.listen(3000)
script.js
const socket = io('/')
const myPeer = new Peer(undefined, {
host:'/',
port:'3002'
})
myPeer.on('open', id => {
socket.emit('join-room', ROOM_ID, id)
})
socket.emit('join-room', ROOM_ID, 10)
socket.on('User-connected', userId => {
console.log('User-connected:' + userId)
})
Room.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Just Not a Document</title>
<script>
const ROOM_ID = "<%= roomId %>"
</script>
<script defer src="https://unpkg.com/peerjs#1.3.1/dist/peerjs.min.js"></script>
<script src="/socket.io/socket.io.js" defer></script>
<script src="script.js" defer></script>
<style>
#video-grid {
display: grid;
grid-template-columns: repeat(auto-fill, 300px);
grid-auto-rows: 300px;
}
video {
width: 100%;
height: 100%;
object-fit: cover;
}
</style>
</head>
<body>
<div id="video-grid"></div>
</body>
</html>

Related

How to populate the data scraped from API in node js into EJS template

My index.js file on root directory
const express = require("express");
const app = express();
const path = require("path");
const axios = require("axios").default;
const cors = require("cors");
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "/views"));
app.use(
cors({
origin: "http://localhost:3000",
})
);
fetchData = async () => {
const data = await axios.get(
"https://nepse-data-api.herokuapp.com/data/todaysprice"
);
console.log(data);
return data;
};
app.get("/", (req, res) => {
const nepseData = fetchData();
res.render("home.ejs", { nepseData });
});
app.listen(3000, () => {
console.log("listening to port 3000");
});
My home.ejs file on views directory
<!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>
</head>
<body>
<%= nepseData %>
</body>
</html>
The browser is displaying this when I run the server
The API is sending this type of data
I want to show the name and prices on my ejs file. What should I do now??
You have to add await there:
app.get("/", async (req, res) => {
const nepseData = await fetchData();
res.render("home.ejs", { nepseData });
});
And then you can iterate over the data:
<% nepseData.forEach(function(row){ %>
<%= row.companyName %> <%= row.minPrice %>
<% }); %>

How do I onclick/addeventlistener to an EJS template?

I'm trying to build a database using mongodb where it will render to an html page using ejs. Backend is node/express.
How do I link the button to an addeventlistener. EJS documentation is limited and I've read other posts that says ejs only renders html but no other functionality.
Eventually, I would like to use an async/await to link the js with the backend.
Here is my ejs:
<!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>
</head>
<body>
<h1>The Beautiful Game</h1>
<form action="/players" method="POST">
<input type="text" placeholder="name" name="name" />
<input type="text" placeholder="club" name="club" />
<button type="submit" class='submitButton'>Submit</button>
</form>
<h2>Players</h2>
<ul class="players">
<% for (var i = 0; i < players.length; i++) {%>
<li class="players">
<span><%= players[i].name %></span>:
<span><%= players[i].club %></span>
<button class="dataDeleteNameButton" data-id="<%=players[i]._id%>">Delete</button> <!-- linking this button -->
</li>
<% } %>
</ul>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
Here is my js:
document
.querySelector("dataDeleteNameButton")
.addEventListener("click", deleteEntry);
async function deleteEntry() {
console.log("Button is working!");
}
Here is the server, if needed:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const cors = require("cors");
const MongoClient = require("mongodb").MongoClient;
const PORT = process.env.PORT || 8000;
app.use(cors());
const username = "hidden";
const password = "hidden";
const connectionString = `mongodb+srv://${username}:${password}#cluster0.7k2ww.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`;
MongoClient.connect(connectionString, { useUnifiedTopology: true })
.then((client) => {
console.log("Connected to database");
const db = client.db("soccer-players");
const playerCollection = db.collection("players");
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static("public"));
app.get("/", (req, res) => {
db.collection("players")
.find()
.toArray()
.then((result) => {
res.render("index.ejs", { players: result });
})
.catch((error) => console.error(error));
});
app.get("/api/players", (req, res) => {
db.collection("players")
.find()
.toArray((err, arr) => {
res.json(arr);
});
});
app.post("/players", (req, res) => {
playerCollection
.insertOne(req.body)
.then((result) => {
res.redirect("/");
})
.catch((error) => console.error(error));
console.log(req.body);
});
app.delete("/", (req, res) => {
// playerCollection.deleteOne() <--
// let findID =
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
})
.catch((error) => console.error(error));
Picture of what it looks like:
This is my script tag path: ../client-side-folder/js-folder/main.js
Directory:
main-folder
+--client-side-folder
+----js-folder
+------main.js
+--views-folder
+----index.ejs
You can just do onclick="myFunction(theIdOfTheButtonHere)"
Here is an example:
https://www.w3schools.com/jsref/event_onclick.asp

socket.io Connection Problem node.js Hosted on Domain

I have tried a million different ways to connect via socket.io.
I keep getting the following error:
WebSocket connection to 'wss:/example.com/socket.io/?EIO=3&transport=websocket&sid=CiLGqnUNiDKvOsreAAAW' failed:
server.js
const { v4: uuidV4 } = require('uuid')
const express = require('express')
const app = express()
const PORT = process.env.PORT || 443;
const fs = require('fs')
const https = require('https')
const options = {
key:fs.readFileSync('server-key.pem', 'utf8').toString(),
cert: fs.readFileSync('server-cert.pem', 'utf8').toString()
}
const httpsServer = https.createServer(options, app)
const io = require('socket.io')(httpsServer)
app.set('view engine', 'ejs')
app.use(express.static('public'))
app.get('/', (req, res) => {
res.redirect(`/${uuidV4()}`)
})
app.get('/:room', (req, res) => {
res.render('room', { roomId: req.params.room })
})
io.on('connection', socket => {
socket.on('join-room', (roomId, userId) => {
socket.join(roomId)
socket.to(roomId).broadcast.emit('user-connected', userId)
socket.on('disconnect', () => {
socket.to(roomId).broadcast.emit('user-disconnected', userId)
})
})
})
httpsServer.listen(PORT, () => console.log(`Server is running on PORT ${PORT}`));
scripts.js
const socket = io.connect('https://example.com:443')
const videoGrid = document.getElementById('video-grid')
const myPeer = new Peer(undefined, {})
const myVideo = document.createElement('video')
myVideo.muted = true
const peers = {}
navigator.mediaDevices.getUserMedia({
video: true,
audio: true
}).then(stream => {
addVideoStream(myVideo, stream)
myPeer.on('call', call => {
call.answer(stream)
const video = document.createElement('video')
call.on('stream', userVideoStream => {
addVideoStream(video, userVideoStream)
})
})
socket.on('user-connected', userId => {
connectToNewUser(userId, stream)
})
})
socket.on('user-disconnected', userId => {
if (peers[userId]) peers[userId].close()
})
myPeer.on('open', id => {
socket.emit('join-room', ROOM_ID, id)
})
function connectToNewUser(userId, stream) {
const call = myPeer.call(userId, stream)
const video = document.createElement('video')
call.on('stream', userVideoStream => {
addVideoStream(video, userVideoStream)
})
call.on('close', () => {
video.remove()
})
peers[userId] = call
}
function addVideoStream(video, stream) {
video.srcObject = stream
video.addEventListener('loadedmetadata', () => {
video.play()
})
videoGrid.append(video)
}
room.ejs
<!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">
<script>
const ROOM_ID = "<%= roomId %>"
</script>
<script defer src="https://unpkg.com/peerjs#1.2.0/dist/peerjs.min.js"></script>
<script src="/socket.io/socket.io.js" defer></script>
<script src="script.js" defer></script>
<title>Document</title>
<style>
#video-grid {
display: grid;
grid-template-columns: repeat(auto-fill, 300px);
grid-auto-rows: 300px;
}
video {
width: 100%;
height: 100%;
object-fit: cover;
}
</style>
</head>
<body>
<div id="video-grid"></div>
</body>
</html>
How can I connect via socket.io? I'm working with my own domain and using cpanel and running node.js.
I am trying to follow the tutorial at: https://github.com/WebDevSimplified/Zoom-Clone-With-WebRTC

GET http://localhost: postman

I'm using MEAN stack as my back-end. this is my server js file
const users = require('./routes/users');
app.get('/', (req, res) => {
res.send('Invalid endpoint');
});
This is my routes file users.js
router.get('/jobdetail', function(req,res) {
console.log('fetching jobs');
jobDetails.find({}, (err,jobs) => {
if(err) {
console.log(err);
}
else {
res.json(jobs);
}
});
});
when I run it the postman bu url:
localhost:3000/api/jobdetail
Instead of the data from MongoDB I get the response as
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
<script type="text/javascript" src="http://gc.kis.v2.scr.kaspersky-labs.com/D11634C0-514E-C94E-9DFD-54EBD0B16E5F/main.js" charset="UTF-8"></script>
</head>
<body>
<pre>Cannot GET /api/jobdetail</pre>
</body>
</html>
var api = require('../routes/users.js');
app.use('/api', api);
in your routes/users.js file :
var mongoose =require('mongoose');
var router = require('express').Router();
var conn = mongoose.connection;
conn.once("open", () => {
router.get('/jobdetail', function(req, res) {
jobDetails.find({}, (err,jobs) => {
if(err) {
console.log(err);
}
else {
res.json(jobs);
}
});
});
});
module.exports = router;

Nodejs spawn remote tail and socket-io to client

I'm fairly new to Nodejs and I'm building an app that ssh to a remote machine and get a tail -f of a log file.
The lines of the log file I'm receiving I'm sending to the client via socket-io (ver. 2.0.3)
Now I'm facing a problem that when a second browser tries to tail a different log, the new log is sent to both of the browsers instead of only the one who made the request.
I'm not sure if it's a problem with my socket-io code or the child_process.
Here's the server:
const express = require('express'),
app = express(),
path = require('path'),
bodyParser = require('body-parser'),
logger = require('morgan'),
server = require('http').Server(app),
io = require('socket.io')(server),
spawn = require('child_process').spawn,
events = require('events'),
eventEmitter = new events.EventEmitter();
// Fix body of requests
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// Log the requests
app.use(logger('dev'));
// Serve static files
app.use(express.static(path.join(__dirname, '.')));
// Add a basic route – index page
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
io.on('connection', (socket) => {
console.log(`client connected ${socket.client.id}`);
eventEmitter.on('tail', (data) => {
socket.tail = spawn('ssh', ['root#' + 'quality-p.company.com', 'tail -f', data.service], { shell: true });
socket.tail.stdout.on('data', (data) => {
console.log(`got new data ${data.toString()}`);
socket.emit('newLine', {line: data.toString().replace(/\n/g, '<br />')});
});
});
});
app.get('/tail', (req, res) => {
eventEmitter.emit('tail', req.query);
res.sendStatus(200);
});
// Bind to a port
server.listen(3005, () => {
console.log('running on localhost:' + 3005);
});
Client:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="./node_modules/socket.io-client/dist/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(() => {
let socket = io();
socket.on('connect', () => {
console.log('connected');
});
socket.on('newLine', (data) => {
console.log(`new data: ${data.line}`);
$("#tailing").append(data.line);
});
$('#tail').click(() => {
$.get('/tail', {
service: $('#service').val()
});
});
});
</script>
<title>Title</title>
</head>
<body>
<select id="service">
<option id="tnet" value="/var/log/tnet">tnet</option>
<option id="consul" value="/var/log/consul">consul</option>
</select>
<button id="tail">tail</button>
<div id="tailing" style="background-color: antiquewhite;">
</div>
</body>
</html>
Server
const express = require('express'),
app = express(),
path = require('path'),
bodyParser = require('body-parser'),
logger = require('morgan'),
server = require('http').Server(app),
io = require('socket.io')(server),
spawn = require('child_process').spawn;
// Fix body of requests
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
// Log the requests
app.use(logger('dev'));
// Serve static files
app.use(express.static(path.join(__dirname, '.')));
// Add a basic route – index page
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
var tails = {};
io.on('connection', (socket) => {
console.log(`client connected ${socket.client.id}`);
socket.on('tail', (data) => {
socket.join(data.service);
if (typeof tails[data.service] == "undefined") {
tails[data.service] = spawn('ssh', ['root#' + 'quality-p.company.com', 'tail -f', data.service], {
shell: true
});
tails[data.service].stdout.on('data', (data) => {
console.log(`got new data ${data.toString()}`);
io.to(data.service).emit('newLine', {
line: data.toString().replace(/\n/g, '<br />')
});
});
}
});
});
// Bind to a port
server.listen(3005, () => {
console.log('running on localhost:' + 3005);
});
Client
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="./node_modules/socket.io-client/dist/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(() => {
let socket = io();
socket.on('connect', () => {
console.log('connected');
});
socket.on('newLine', (data) => {
console.log(`new data: ${data.line}`);
$("#tailing").append(data.line);
});
$('#tail').click(() => {
socket.emit('tail', {
service: $('#service').val()
});
});
});
</script>
<title>Title</title>
</head>
<body>
<select id="service">
<option id="tnet" value="/var/log/tnet">tnet</option>
<option id="consul" value="/var/log/consul">consul</option>
</select>
<button id="tail">tail</button>
<div id="tailing" style="background-color: antiquewhite;">
</div>
</body>
</html>

Resources