Home
Tools
Workshops
Technologies
Pricing
Contact Us



How to make a Music Server with Nodejs & Express

Learn how to build a Nodejs App that serves Music

nodejs music server
What do we intend to make in this tutorial?
Our mission in this article is very precise and focussed. We want to build an app which lets a user perform 2 actions:
  1. Listen to a song or mp3 file by clicking a button in his broswer
  2. Download a music file by clicking on a button
Learning objective, what to expect?
The music server app we build in this tutorial will help us to brush our fundamental understanding of following Node.js and Express.js concepts:
  1. Piping Streams in Nodejs
  2. Reading Files only after verifying that they Exist
  3. Serving static content and streams in express
Lets get Coding!
Start by creating an npm package for your Nodejs app. In your shell or command prompt, move to the directory where you would like to create your project and type npm init which opens an interactive session for creation of the package.json file. Choose a name for your package and a good description. NPM will help you with default options where ever possible. Typical package creation flow using npm is shown below:

	npm init
	Press ^C at any time to quit.
	name: (express-music) express-music
	version: (1.0.0) 
	description: music app with nodejs and expressjs by rishabh
	entry point: (index.js) app.js
	test command:
	git repository: https://github.com/rishabhio/ExpressMusic.git
	keywords: node,music-server,express,streams,pipe
	author: @rishabhio
	license: (ISC) MIT
	About to write to ~home\express-music\package.json:
	{
		"name": "pckgtest",
		"version": "1.0.0",
		"description": "",
		"main": "index.js",
		"scripts": {
			"test": "echo \"Error: no test specified\" && exit 1"
		},
		"repository": {
			"type": "git",
			"url": "git+https://github.com/rishabhio/ExpressMusic.git"
		},
		"keywords": [
			"express",
			"node",
			"music-server"
		],
		"author": "@rishabhio",
		"license": "MIT",
		"bugs": {
			"url": "https://github.com/rishabhio/ExpressMusic/issues"
		},
		"homepage": "https://github.com/rishabhio/ExpressMusic#readme"
	}


Is this ok? (yes) yes

	
Once you've the package.json ready, just install express by running the following in your command shell:

	npm install express --save
Now create a file app.js and add the following code to it. Please read the comments given along the code lines to understand what the code is intended for.

/** 
	app.js
	@author: @rishabhio
	@description: Implementing Simple Music Server using Express JS 
	
**/

// import the modules required in our program
var express = require('express');
var fs = require('fs');

// initialize an express app
var app = express();

// declare public directory to be used as a store for static files
app.use('/public', express.static(__dirname + '/public'));


// make the default route to serve our static file 
app.get('/',function(req,res){
	
	return res.redirect('/public/home.html');

});

// start app on port 3003 and log the message to console

app.listen(3003,function(){
	console.log('App listening on port 3003!');
});



What we did in the above code:
  1. Initialized an express app
  2. Made public directory a store for serving static files
  3. Set the default route to redirect to home.html file in public directory
before you try to run the above code, make sure to create the public directory using mkdir command

	mkdir public
Now add 2 more routes to your app.js file as defined below for downloading and streaming music.



// define a route music it creates readstream to the requested file and pipes the output to response

app.get('/music', function(req,res){
	
	var fileId = req.query.id; 
	var file = __dirname + '/music/' + fileId;
	fs.exists(file,function(exists){
		if(exists)
		{
			var rstream = fs.createReadStream(file);
			rstream.pipe(res);
		}
		else
		{
			res.send("Its a 404");
			res.end();
		}
	
	});
});

// following is the code for downloading music files, note that the code remains same except that we add 2 headers viz
// Content-disposition and Content-Type which forces the chrome browser to force download rather than playing the media
// Note that the following is tested with google chrome and it may work differently in Mozilla and Opera based on your 
// installed plugins.

app.get('/download', function(req,res){
	var fileId = req.query.id;
	var file = __dirname + '/music/' + fileId;
	fs.exists(file,function(exists){
		if(exists)
		{
			res.setHeader('Content-disposition', 'attachment; filename=' + fileId);
			res.setHeader('Content-Type', 'application/audio/mpeg3')
			var rstream = fs.createReadStream(file);
			rstream.pipe(res);
		}
		else
		{
			res.send("Its a 404");
			res.end();
		}
	});
});
So we defined 2 routes:
  1. To let the users download requested mp3 files
  2. To let the users listen to the requested mp3 files
Now create a directory music.

	mkdir music
You can add as many music files to your music directory as you like but for this app, we added 3 files with following names:
  1. hello.mp3
  2. divine.mp3
  3. beginning.mp3
Note that we've not provided mp3 file in our tutorial or repo to reduce the repo size. Just rename any mp3 files on your machine to the above names and copy them in the music directory.
Add Static Files to Public Directory!
Following are the contents of the home.html file. Note that we've used bootstrap and an image file which are present in our github repo


<!DOCTYPE html>
<html>
<head>
	<link rel="stylesheet" href="bootstrap.min.css" type="text/css">
	<title> Express Music Server </title>
	<style>
		body {
		
			padding: 30px;
			background: url('./bg-musical.png');
			text-align: center;
		}
		.contents{
			background: #fff;
			padding: 20px;
			margin: auto;
			opacity: 0.7;
			text-align: center;
		}
		.contents button{
			width: 100px;
			opacity: 0.9;
			background: #000;
		}
		h1 {
			color: #333333;
			font-size: 60px;
		}
		h2 {
			color: #2e2e2e;
			font-size: 28px;
		}
		a {
			color: #2f2f2f;
			font-size: 18px
		}
		
	</style>
</head>
<body>
	<div class="container contents">
	<h1>  Express Musical </h1>
	<hr>
	<h2> Fast Music to Keep you surrounded with Melodic Beats </h2>
	<hr>
	<a href="https://rishabh.io">  Rishabh IO	</a> 
	
	
		<div class="row">
			<div class="col-md-4">
				<img class="img img-responsive" src="song.png"/>
				<h2> hello.mp3 </h2>
				
				<a href="http://localhost:3003/music?id=hello.mp3" target="_blank"> <button class="btn btn-success"> Play </button>	</a> <hr>
				<a href="http://localhost:3003/download?id=hello.mp3"  target="_blank"> <button class="btn btn-success"> Downnload </button> </a>
			</div>
			<div class="col-md-4">
			<img class="img img-responsive" src="song.png"/>
				<h2> divine.mp3 </h2>
				<a href="http://localhost:3003/music?id=divine.mp3" target="_blank"> <button class="btn btn-success"> Play </button>	</a> <hr>
				<a href="http://localhost:3003/download?id=divine.mp3"  target="_blank"> <button class="btn btn-success"> Downnload </button> </a>
			</div>
			<div class="col-md-4">
			<img class="img img-responsive" src="song.png"/>
				<h2> beginning.mp3 </h2>
				<a href="http://localhost:3003/music?id=beginning.mp3" target="_blank"> <button class="btn btn-success"> Play </button>	</a> <hr>
				<a href="http://localhost:3003/download?id=beginning.mp3"  target="_blank"> <button class="btn btn-success"> Downnload </button> </a>
			</div>
		</div>
	</div>
	
</body>
</html>





Note that we're assuming here that the app is being run on localhost and port 3003. In case you plan to change the port number, you'll need to manually change the links in the home.html file.
Time to Run our Music Server
It's finally the time to see the wonderful little thing we've just created in action. Run the following command in your command shell and go to your browser at http://localhost:3003

		node app.js
Feel the melody in the Air!
Just click on the play button and it should start playing the corresponding music files you stored in the music directory of the app. We can keep on adding files and we can also automate adding more and more html links but for this tutorial, it's left as an exercise. Following is a screen shot of our app.
serving music files using express
Download the code from GITHUB!
Just in case you've not done so, you can download the code for this app from github by issuing the following command in your terminal or git bash

		git clone https://github.com/rishabhio/ExpressMusic.git
Conclusion!
In this tutorial, we learned how to build a simple music app server in Nodejs and Express. This simple app can be used as a starting point to build something more complex and usable in real world.

More from RISHABH.IO







developed & nourished with by rishabh.io