Can't hide file extension in NODE.js - node.js

I want to hide a file extension and folder from url. So I wrote such code, that I suppose would work.
Physical path to file is /data/users.json . In url i want to get 200 response if user enteres localhost:3000/api/users
But I've been getting 404 . And if I enter localhost:3000/api/users.json - 200 instead of 404 (
const express = require('express');
const path = require('path');
const fs = require('fs');
const app = express ();
const PORT = 3000;
app.use('/api', express.static(path.join(__dirname,'data')) );
app.get('/api/:name',(req,res) => { //http://expressjs.com/en/guide/routing.html#route-parameters
let {name}=req.params;
const filename= name+'.json'; //adding extension
fs.open(filename, 'r', (err, fd) => { //https://nodejs.org/api/fs.html#fsopenpath-flags-mode-callback
if (err) {
if (err.code === 'ENOENT') {
console.log(filename);
res.status(404 );
res.end('404 '+filename);
return;
}
throw err;
}
try {
res.json(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
});

Related

Socket.io Blocked loading mixed active content Error

I have a chat app i'm building, it works fine offline but in production, it refuses to connect and it gives out this error in the browser.
Blocked loading mixed active content
here is the code for the back end app.js
const http = require("http");
const express = require("express");
const app = express();
const path = require("path");
const server = http.createServer(app);
const dotenv = require("dotenv").config();
const router = require(path.join(__dirname + "/modules/router.js"));
const mongoose = require("mongoose");
const URL = process.env.DB_URL;
const Schema = require(path.join(__dirname + "/modules/Schema.js"));
const io = require("socket.io")(server, {
cors: {
origin: "*",
},
});
app.use(router);
mongoose.connect(URL, (err) => {
if (err) throw err;
else {
server.listen(process.env.PORT, console.log("Server is running"));
}
});
io.on("connection", (socket) => {
let payload = socket.handshake.auth.$token;
socket.emit("thru", true);
socket.on("join", async (link, cb) => {
// Checking users
Schema.Link.findOne({ code: link }, (err, d) => {
if (err || d == " ") cb(false, false);
else {
if (d.onlineUsers.length < 2) {
if (d.onlineUsers.includes(payload)) {
cb(true, true);
} else {
// Adding user
d.onlineUsers.unshift(payload);
Schema.Link.findOneAndUpdate(
{ code: link },
{ onlineUsers: d.onlineUsers },
(err, x) => {
if (err || x == "") cb(false, false);
else {
if (x.onlineUsers.length == 1) cb(true, true);
else cb(true, false);
}
}
);
}
} else cb(false, false);
}
});
socket.join(link);
socket.broadcast.to(link).emit("online", true);
socket.on("message", (m, cb) => {
m.date = new Date();
socket.broadcast.to(link).emit("broadcast", m);
cb(m);
});
});
socket.on("disconnect", (data) => {
const $link = socket.handshake.auth.$link;
Schema.Link.findOne({ code: $link })
.then((x) => {
if (x == "") console.log("user not found");
else {
let n = x.onlineUsers.filter((c) => c !== payload);
Schema.Link.findOneAndUpdate(
{ code: $link },
{ onlineUsers: n },
(err) => {
if (err) console.log(err);
else {
socket.broadcast.to($link).emit("online", false);
}
}
);
}
})
.catch((e) => {
console.log("Ending", e);
});
});
});
And here is the front end chat screen
useEffect(() => {
try {
socket.current = io("http://chatterbox-v2-api.vercel.app", {
auth: {
$token: localStorage.getItem("senders_token"),
$link: link,
},
});
} catch (err) {
console.log("Error");
}
i've tried hosting the scoket server on another platform but nothing.
I think the problem here is that you are trying to reach a HTTP server (http://chatterbox-v2-api.vercel.app) from a page served with HTTPS, which triggers an "Blocked loading mixed active content" error.
Reference: https://developer.mozilla.org/en-US/docs/Web/Security/Mixed_content
Is your server available with HTTPS (https://chatterbox-v2-api.vercel.app)?

I have a problem with node js rtsp streaming server

I made rtsp cctv streaming server with nodjs.
But it is not stable.
Some cctvs works well but others are not.
First I thought rtsp url has its own problem, but it may not.
Because the url worked well in vlc player.
I don't know what I'm missing.
below is my whole code related cctv streaming.
var express = require('express');
var router = express.Router();
var kill = require('tree-kill');
var fs = require('fs');
var path = require('path');
var ffmpeg = require('fluent-ffmpeg');
var ffmpegInstaller = require('#ffmpeg-installer/ffmpeg');
ffmpeg.setFfmpegPath(ffmpegInstaller.path)
var streams = {};
//start cctv
router.post('/', (req, res) => {
var cname = req.body.cname;
var url = req.body.url;
//if there is same cctv name
if(streams[cname] != null) {
res.status(409).send("duplicate name");
return;
};
//create dir as given cctv name;
mkdir(cname);
stream = ffmpeg(url).addOptions([
'-hls_time 5',
'-hls_list_size 10',
'-hls_flags delete_segments',
'-f hls'
]).output('./public/video/' + cname + '/' + cname + '.m3u8'); //save path
console.log("Start cctv streaming");
stream.on('error', function(err, stdout, stderr) {
console.log("cctv has been stoped");
console.log(err);
});
stream.run();
streams[cname] = stream;
res.status(201).send("OK");
});
//bring cctv pid by cctv name
router.get('/:cname', (req, res) => {
var cname = req.params.cname;
if(streams[cname] == null) {
res.status(404).send("not found such a cctv");
return;
};
var pid = streams[cname].ffmpegProc.pid;
res.send({"pid": pid});
});
//stop cctv by pid
router.delete('/:cname', async (req, res) => {
var cname = req.params.cname;
//no cctv
if(streams[cname] == null) {
res.status(404).send("not found such a cctv");
return;
};
//del dir
var filePath = './public/video/' + cname;
fs.rmdir(filePath, { recursive: true }, (err) => {
if (err) {
console.log(err)
} else {
console.log('dir is deleted.');
}
});
//var pid = streams[cname].ffmpegProc.pid;
streams[cname].kill();
res.status(204).send("OK");
});
const mkdir = (name) => {
var root = './public/video/';
if(!fs.existsSync(root + name)){
fs.mkdirSync(root + name);
}
}
And this is ts file save folder.
cctv1 dosen't work well but cctv2 works well.
(cctv1 started first but created less ts file than cctv2.)

Azure: INFO - Waiting for response to warmup request for container ... Elapsed time = x sec

My app fails on prod and can't find a way how to fix. It works on another environments.
Some logs from the console:
2022-08-22T23:56:05.760Z INFO - Waiting for response to warmup request for container projectprod-fe_0_fd84e. Elapsed time = [225.2643051] sec
2022-08-22T23:56:35.818Z ERROR - Container projectprodfe_0_fd84e for site teamgullitpreview-fe did not start within expected time limit. Elapsed time = 255.322965 sec
It is next.js app and I create middlewares for it.
const next = require('next');
const { parse } = require('url');
nextMiddleware
async function nextMiddleware(dev = false) {
const app = next({ dev });
const handle = app.getRequestHandler();
await app.prepare();
return function nextHandler(req, res) {
const parsedUrl = parse(req.url, true);
handle(req, res, parsedUrl);
};
}
redirectMiddleware
const path = require('path');
const fs = require('fs');
const staticFiles = ['_next', '/', 'images', 'api'];
const getRedirect = async (srcPath) => {
try {
const url = `${process.env.NEXT_PUBLIC_apiUrl}/redirect?path=${srcPath}`;
const response = await fetch(url);
const json = await response.json();
return json;
} catch (e) {
throw new Error(e);
}
};
function redirecter(pathname) {
return new Promise((resolve, reject) => {
const pathParts = pathname.split('/');
if (staticFiles.indexOf(pathParts[1]) > -1) {
resolve({
shouldRedirect: false,
redirectData: {},
});
} else {
const possibleFile = `${path.resolve(
__dirname,
'../../public',
)}${pathname}`;
if (fs.existsSync(possibleFile)) {
resolve({
shouldRedirect: false,
redirectData: {},
});
} else {
getRedirect(pathname)
.then((result) => {
resolve({
shouldRedirect: true,
redirectData: result,
});
})
.catch((e) => {
reject(e);
});
}
}
});
}
async function redirectMiddleware(req, res, next) {
const parsedUrl = parse(req.url, true);
const { pathname } = parsedUrl;
try {
const { shouldRedirect, redirectData } = await redirecter(pathname);
if (shouldRedirect && redirectData.destination) {
const redirectUri = `${process.env.NEXT_PUBLIC_hostname}${
redirectData.type ? redirectData.type : ''
}${redirectData.destination}`;
res.writeHead(redirectData.statusCode[0], {
Location: redirectUri,
});
res.end();
}
} catch (e) {
next();
} finally {
next();
}
}
What I do wrong in this file or whenever?
const http = require('http');
const express = require('express');
const redirectMiddleware = require('./src/server/redirectMiddleware');
const nextMiddleware = require('./src/server/nextMiddleware');
const port = process.env.PORT || 3000;
async function bootstrap() {
const isDevelopment = process.argv.includes('--dev');
const app = express();
app.use(await redirectMiddleware);
app.use(await nextMiddleware(isDevelopment));
const server = http.createServer(app);
server.listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
}
bootstrap().catch((err) => {
console.error('something went wrong booting up the server.');
console.error(err);
process.exit(1);
});
I have no idea what's wrong and how to debugg it. Is anyone who experienced it before?

How to read all file with specified ext in a dir?

I am new to nodejs and want this to work.
var fs = require('fs');
fs.readdir("dir", function(err, files) {
if (err) return;
files.forEach(function(f) {
data = []
if f.extension = "rtf"
data = data + f.data
});
});
You can try this :
const fs = require('fs');
const path = require('path');
fs.readdir("dir", (err, files) => {
if (err) return;
files.forEach(f => {
let data = []
const ext = path.extname(file)
if (ext == ".rtf") {
fs.readFile(f, function read(err, content) {
if (err) {
throw err;
}
data.push(content);
});
}
});
});
You will have each content of the files under the array data. But it will be better to put it into an object to know where the content come from like this :
const fs = require('fs');
const path = require('path');
fs.readdir("dir", (err, files) => {
if (err) return;
files.forEach(f => {
let data = {}
const ext = path.extname(file)
if (ext == ".rtf") {
fs.readFile(f, function read(err, content) {
if (err) {
throw err;
}
data[f] = content;
});
}
});
});

node.js (or nwjs) ftp download

Need to download new files periodicaly from public ftp:
ftp://ftp.cmegroup.com/bulletin/
But I cannot connect ftp module to sever. My code is:
var url = "ftp://ftp.cmegroup.com/bulletin/";
var path = require('path');
var fs = require('fs');
//var Promise = require('bluebird');
var Client = require('ftp');
var c = new Client();
var connectionProperties = {
host: "ftp.cmegroup.com",
};
c.on('ready', function () {
console.log('ready');
c.list(function (err, list) {
if (err) throw err;
list.forEach(function (element, index, array) {
//Ignore directories
if (element.type === 'd') {
console.log('ignoring directory ' + element.name);
return;
}
//Ignore non zips
if (path.extname(element.name) !== '.zip') {
console.log('ignoring file ' + element.name);
return;
}
//Download files
c.get(element.name, function (err, stream) {
if (err) throw err;
stream.once('close', function () {
c.end();
});
stream.pipe(fs.createWriteStream(element.name));
});
});
});
});
c.connect(connectionProperties);
Error:
Uncaught Error: connect ECONNREFUSED 127.0.0.1:21
Can't understand why it connects to localhost despite I pointed connection params.
lack of one line
c.connect(connectionProperties);

Resources