How to stream a media file from server to client side for example an mp3 audio file in my case in loopback 4 nodejs? - node.js

I have loopback 4 - nodejs in the backend and Ionic 4 in the frontend of my mobile application. I'm storing an mp3 file on server sid and I want to stream and play it on the client-side so basically audio streaming from loopback4.
So basically I'm looking for server-side code in loopback-4 which is in typescript to audio-stream a file to client. (I'm unable to use npmjs libraries since most of them are not typed and cannot be used in typescript)

As soon as I know about loopback4, it doesn't have nodejs stream implementation. I recommend you to use native NodeJS streams. Check out this repo https://github.com/noamtcohen/AudioStreamer

Short answer:
I was able to achieve this by simply serving static files i.e my audio file from the server-side. Accessing it using the endpoint I made and calling it using the tag on the frontend.
Long answer:
In loopback 4, you can find a line of code in application.ts file where public directory from the root folder of the server project is served.
this.static('/', path.join(__dirname, '../../public'));
Similarly, you can serve your static files from whatever dir you want. In my case, I served my files from media folder which I added in the root directory of my node project.
this.static('/', path.join(__dirname, '../media'));
The second step is to expose an API endpoint which you would use to make a get request to the server. You can do that inside index.ts file of the server project and the code right below app.start().
app.static('/media', 'media', { extensions: ['mp3'] });
Here, adding the API endpoint and the directory in the root folder of the node project is mandatory.
Now, on the frontend you only have to add your complete url to access the static file from node project to the src attribute of html tag.
Add controls attribute to the tag and html will handle everything for you. You can play, pause, skip, etc.
<audio controls #audioElement id="id1" [src]="http://localhost:3000/media/audio-files/myAudiofile.mp3">

Related

How to change the default path assets are served in SvelteKit?

I created a sample app using SvelteKit to perform SSR. I noticed the svelte assets are always downloaded following this path _app/immutable/.. (examples):
http://localhost:3000/_app/immutable/start-9080d3a7.js
http://localhost:3000/_app/immutable/chunks/index-cad423a5.js
http://localhost:3000/_app/immutable/layout.svelte-eb403b25.js
http://localhost:3000/_app/immutable/pages/up-homeui/index.svelte-d6a3b39b.js
http://localhost:3000/_app/immutable/error.svelte-3f23e1a2.js
How can I serve the assets at the root level, like:
http://localhost:3000/start-9080d3a7.js
http://localhost:3000/index-cad423a5.js
http://localhost:3000/layout.svelte-eb403b25.js
http://localhost:3000/index.svelte-d6a3b39b.js
http://localhost:3000/error.svelte-3f23e1a2.js
At the end, I would like to serve all the files at the same level.
I already played with the svelte.config and the vite.config but I couldn't find a way to change this default behavior.

Angular application files upload

It's a first time I'm doing this so got some trivial (I think) problems with files upload.
I have a pair: Angular 7 app + NodeJS (express) backend. I successfully uploading files (images) through the Angular page, NodeJS save it with correct format, but I don't know what can I do to be able to target just uploaded images in my web-service and where should I store new files. Should it be : src/app/uploads or only src/app ? Can someone explain the idea behind.
Do I need to do any extra actions in Angular? Because it shows me 404 page if I try to target something out of scope of the app.
Thanks!
I think that src directory should store only source code (or something change when you update your version of code)
In my opinion, uploaded file shouldnt be stored in src directory.
Maybe
Root dir
- docs
- migrations
- node_modules
- src
- tmp
- uploaded
.......

Can't show static loaded videos by Express.js

I'm serving some static HTML, CSS and JS files and also a folder called tmp with some images and video files using Express.js for my Node app:
app.use(express.static("build"));
app.use(express.static("../tmp"));
When I go to http://localhost:3003, it loads up my app very nicely and it loads all the images on my webpage(located in the tmp folder) but the problem is every video file looks like this:
If I press fullscreen on the video player or even visit the url directly http://localhost:3003/video_1.mp4, it works.
Is this a problem with Express.js trying to stream the video data from the tmp folder? I really don't know how to solve this issue. I tried to delay the playback and use a 3rd party library to play the video but no luck.
Seems to work when I directly specify the whole path localhost:3003/picture.png in src of the video element

Why can't I require files which are available due to app.use?

If a directory has been made available to a node application in the server.js file which sits in the main directory using:
app.use("/scripts",express.static(__dirname + "/scripts"));
and I attempt to use require from a file inside of that directory (/scripts/custom.js) using:
var Testing123 = require('../app/models/article');
Is there a reason this is not possible? and is there a solution to that problem?
Edit: In one of my views (views/tree.ejs) I use:
<script type="text/javascript" src="../scripts/custom.js"></script>
to access my Custom script which sits inside my scripts folder which is made available using express.static, Custom uses a web scraper to scrape articles and present them in circles (in the form of an image, title and link) on views/tree.ejs, I now want custom.js to save each article it creates to a mongodb database but to do so, it needs access to things like my Article Schema hence the problem above.
You cannot because Node.js scripts and browser scripts do not run in the same context. Your app.use call just exposes a /scripts route that serves assets statically on your HTTP Server.
Your scripts/custom.js script seems to be a browser-side script (Because you load it with a script tag inside an ejs view) but you want to use require inside it and this will not work as this is a Node.js function.
Have a look at LearnYouNode which is an excellent Node beginner tutorial so that you will understand how modules work in Node and know a bit more about the separation between server-side and client-side JS.

Working with Node.JS

Last night I dump windows 7 and formatted my hard driver to port to a Linux based operating system, Purely for the reasons that I wanted to start working with Node.JS
So I have installed Node.JS and have done a few test stuff, the http server and sockets etc.
What I would like to do is build a HTTP Server that is tightly intergrated with an MVC Framework, but before I get started on all that I need to learn how to build efficiently in Node.
For example within PHP as my framework I would create a bootloading system to load all base classes etc, then i would fire my events system ready to start attaching callbacks.
I would continue to process the request etc until the output is generated which then gets sent of to an output handler that would process headers etc etc
But Node s a totally new environment for this and im wondering on the best practises to build an system in Node.
The information im looking for is more to do with the design structure rather then the actual coding of the application, how to load the lib where to load the libs, etc etc
Any help is appreciated.
So far my WebApplication is coming along nicely, I have built my application pretty traditionally and a little procedural.
What i have started out is creating a directory structure like so:
<root>
startup.js
/public/
favicon.ico
/images/
/stylesheets/
/javascripts/
/system/
init.js
config.js
/libs/
/exceptions/
http.js
server.js
/application/
/views/
/_override/
/errors/
generic.view
/partials/
sidebar.voew
index.view
/controllers/
index.js
/models/
users.js
This directory structure is like most MVC Based Web Applications out there so using this method I feel comfortable.
The startup file is whats executed by node as the entry point, node startup & and looks like so:
/*
* Header of t he file, Copyright etc
*/
var _Intitialize = require("./system/init.js");
//Displays the command line header, title, copyright etc
_Intitialize.DisplayCommandLineHeader();
//Check the enviroment, Permissions, Ports etc
_Intitialize.CheckEnviroment();
//Start the server and listen the port.
_Initialize.StartServer();
the init file is the main work, its what tells all other areas of the system to run, stop etc.
I have a file in libs called serverhandler.js, and this is required into init.js, I then create a server and assign the callback to the ServerHandler.Listener. Who then listens for requests, checks to see if the file exists in public directory, if so it then reads in chunks and sends back.
if no file was found in public it would then create a route with Route.Create("/path?params"); which deters 3 elements, Controller, Method, Params from the uri, and then the controller files are loaded if exists.
I've taken on the approach of throwing error pages like so:
if(!FileSystem.exists(RequiredPath))
{
throw new HTTPExceptions.FileNotFound();
}
Hope this helps some people getting started in Node.
Have a look at
http://dailyjs.com/2010/11/01/node-tutorial/ , it's pretty relevant.
I would suggest looking at the current modules too
https://github.com/joyent/node/wiki/modules
and reading the code of any of the projects in the areas you are interested in, esp. the middleware, routing and module loaders.

Resources