Effective JavaScript & How to behave when you sit next to Douglas Crockford

Before I go into the most unique experience I had with Douglas Crockford, I want to put down the real essence of this post, which is the notes I took in the Effective JavaScript session that I attended. The most important thing I learnt in the training is the first line in my notes (the rest is secondary and you can actually skip it and move on to other things if you like)

All work you do must stem from Service to Humanity

  • Programming Style is important. But style is not about personal expression via code.
  • Write code that is easy to read, share, improve and expand upon.
  • Look at programs as literary work
  • We are paid to write programs that work well and are free of errors
  • Read Thinking fast & slow by Daniel Kahneman
  • There is no way of testing a program to check if it s 100% perfect, hence it’s all about perfection for programmers
  • When people argue about something technical, they speak from an inner emotional space which may not be necessarily logical
  • If someone says, “That hardly happens“, they actually mean, “It happens!
  • The origin of word processing: Authors had no control over presentation
  • CSS has lead to classitis and iditis
  • In JavaScript, if you take this out, what you are left with is a functional programming language, which is great
  • Use TitleCase only for constructor functions
  • An activation record is created every time a variable is needed
  • Closures are great coz they don’t keep variables in the stack, instead they keep it in the heap
  • Avoid globals. In this statement, b is a global: var a = b = 0;
  • Doug feels, Ken Thompson is the most amazing programmer ever. He created B, C, Regular Expressions, Unix, UTF-8 etc.
  • Buffer overruns come from using ++. Hence use += instead.
  • The Mosaic browser was instrumental in popularizing the world wide web. It was graphical, had support for multiple internet protocols, it displayed images inline (instead of separate windows)
  • Objects in JavaScript work by the principle of differential inheritance where an object maintains a reference to its prototype from a table of properties. It creates a new property in the table only if it is different than its reference
  • The splice command is slow
  • 0.1 + 0.2 === 0.3 // this returns false as it s really difficult for the computer to represent certain floating point numbers. In this example, adding 0.1 and 0.2 actually results in 0.30000000000000004 which is not 0.3
  • Choose to loop over Object.keys instead of for (var i in obj)
  • Choose function expression over function statement
  • JavaScript has function scope (not block scope) but block scope will be added in ES6
  • Binding of this happens late (at invocation point) This is done to preserve memory
  • If you do something like arr.push(fn), fn has access to arr as this (as arr is to the left of the period) This can be a security loophole
  • Look up and read about Auguste Kerckhoff and his work
  • Look up waterken which makes web services using the Actor model
  • Learn about the Actor model
  • The law of turns must be respected, hence avoid using the sync counterparts of the async functions of node.
  • Douglas Crockford has created a new number type DEC64 which can represent decimal fractions with 16 decimal places which makes it well suited to apps that are concerned with money


Still here?

OK, so here is the unique experience.

Firstly it was a 3 day training. On all 3 days, Douglas came in way before time and stood behind the podium and he looked like Gandalf was checking his email. At the beginning of the training on day 2, he encountered some issues with his tablet and needed to replace it with his laptop which was at his residence. He looked around and asked most politely if anybody had a car and was willing to take him home to get his laptop and get it back just in time for the training. Now this is enough to prompt all the JavaScript programmers in the room to literally go into a frenzy. I mean this was not about 2 spaces in a tab OR 4… it was not about soft tabs OR hard, it was not about === OR == and it was certainly not about Angular OR React! This was about getting the opportunity to take Douglas Crockford to ‘his’ house and getting his laptop back in ‘your’ car.

Let’s pause here for a moment to take in the full effect of this eventuality.


Still here!!

Needless to say, and yet I ll add more color and exaggerate in general as I go along… I battled my way through a barricade of jQuery developers who thought they knew JavaScript and went straight for the win!

I was never so eager to drive anyone to their house in my entire life!

Lets take women out of the equation and try to rephrase that.

I was never so eager to drive anyone to their house in my entire life!

That’s right! The sentence doesn’t change. Why should it change? This is Douglas Crockford!

Anyway, so I was obviously a lot more polite and positive. I had a bouncier bounce to my step while escorting him to my car. A million questions were racing through my mind. JavaScript questions, software questions… do you use Sublime or Atom or are you more of a emacs dude? Vim maybe? Do you think the framework that I am good at is the best framework of them all? Node.js or io.js? Should I start using Harmony right away or should I wait for this year to end? Is there a God? No kidding!

When we started toward his house I noticed there was some traffic on the freeway! Never was I so happy to be stuck in traffic! Haha, this was going just perfect.

So I started thinking on the lines of which question to ask first. As some time went by, the questions started melting away or falling apart. I told myself, this guy must’ve been asked all these questions so many times and in so many different ways by so many different people. No amount of rephrasing is going to add any novel juice to any of them. Besides how does it matter? All these  preferences and opinions that developers have. Why should one be better than the other. And even if it is, how much sense does it make to apply any of it without fully understanding it and hence making it your own personal opinion. At the end of the day it’s all about how genuine you are as a human being.

I looked at him. Sitting there. Staring out of the window. I said to myself, ‘Fuck it!‘ I m not asking anything. He s probably going to be asked a whole lot of questions by the ‘JavaScript’ developers waiting back at the training anyway. One less developer may not make a massive difference but these 15 – 20 minutes can be made better for him instead of me. I just drove quietly. We went to his house. He picked his laptop and we drove back. No fanfare, no guru-disciple kinda drama. Nothing. Just a quiet drive. I cannot speak for him, but I had the most amazing time of my computing life for those 3 days.

There are some smart people out there who like to challenge Douglas Crockford’s opinions about JavaScript. In fact they use it as a tool to pronounce their smartness. They cannot create a data exchange format that the world will adopt unanimously. Nor can they create a number type that can aid in applications dealing with finances. And of course they cannot possibly have the first hand historic context that he has. But they continue to think their understanding is way better than his. And I m not going to refute that. I m just gonna save up my questions for them :)

Categories: Javascript | 1 comment

When should you use JavaScript prototype based inheritance?

Not anymore.

But, let’s relive 2006 for a moment. When you needed a new reusable ‘type’ that does not exist, you created a ‘prototype’ of what you need. In other words you created a __proto__ for a new type.


When you do something like the following, you will end up creating a new type called Person. Just like the type String.

Now if you try to do something like

Brendan Eich, in his infinite wisdom (and finite time – 10 days) did not create JavaScript as a new Object Oriented Programming language to compete with Java, but for years people have tried to use the prototype property of Object into making JavaScript work like Java. I d say that right there explains one of the reasons why JavaScript once used to be the most hated programming language of the world. (That and the DOM API). Fortunately times have changed and now, thanks to the never ending libraries and frameworks written in JavaScript along with its ability to go beyond the browser with Node.js, its the world’s most loved language. People are building robots and helicopters with JavaScript!


Here’s a better way to do the same thing as we did above, but this time using Object.create:

Now that looks different. It looks like 2011. And we are already in 2015! So what is the right way to create objects considering that? Functions in JavaScript are first class objects and we can use closures to create modules that will remember the environment they were created in even after the closing function has returned.


As you can see, we have private variables and methods in there. We are only exposing what we want using the revealing module pattern.


The ES6 spec will be ready and available in A Grade browser around later this year or early next and the same will look like this,

The beauty of this is not the syntactic sugar for initializing variable via curly braces and object properties but the Object.freeze method which will prevent anybody from overwriting our exposed methods in case they got access to the object. Essentially making our objects immutable.

Categories: Javascript | Tags: | Leave a comment

Understanding JavaScript closures through the context of Indian classical music and modern art

One good thing about music, when it hits you, you feel no pain.
- Bob Marley

As of EcmaScript 5, closures, along with functions, are at the heart of creating modules in JavaScript. While understanding closures can take some time initially, the effort invested yields great results on the dawn of understanding of what closures are. A “closure” is an expression (typically a function) that returns an object or function along with the environment it was created in, such that it has access to the variables and identifiers from the environment, even after that environment or the function that surrounds (or closes) it, has returned.

In Indian classical music, there is a concept called Raaga. Raaga is like an advanced scale or mode with melody. Using a scale as the means to define a Raaga is like using tap water to explain the concept of rain. But there is really no simpler way to explain this to an audience which comprises of both Indian as well non Indian ‘closure’.

There are many different Raagas. In many cases, a Raaga is explored in a concert by a vocal artist or instrumentalist with an attempt to invoke in the listeners, the original emotion that was responsible for the birth of the Raaga. To give the listeners the same feeling without giving them the circumstances that caused that feeling.

JavaScript closures and Indian classical music

Awareness of the feeling thru the rendition of a Raaga is the transfer of state(emotion) and data(notes) to the listener. Once the listener is one with the feeling that the artist is trying to express, a perfect closure scenario takes place. The feeling the listener gets is the object returned and the rendition itself is the closure. The same analogy can be easily applied to the other art forms. An artist’s painting is the closure and the disturbance or joy derived by soaking oneself in the artwork is the object returned. No wonder then, we feel nothing sometimes when we look at some of the modern art. That happens when the closure fails to return an object along with it’s environment.

To sum it up, closures give out a function or object that remembers the environment it was created in. The general approach to understanding closures is to get as many different perspectives about it till one of ‘em clicks for you. I hope this abstract comparison to art  and music for explaining closures acts as yet another perspective about closures. Happy coding!

Categories: Javascript | Tags: , | Leave a comment

Simple pattern matching with Javascript String.replace

The first rule of any technology used in a business is that automation applied to an efficient operation will magnify the efficiency. The second is that automation applied to an inefficient operation will magnify the inefficiency.
-Bill Gates

For my personal music related project (Scribbletune) I wanted to generate an array of objects from a string. Here are some examples of the input expected and the output desired in each case:

Input (String):

Output(Array of Objects):

What’s happening here is, x denotes a Note On state and one or more underscores following an x denotes the length of the note in units of 32. Each hyphen denotes an interval or a Note Off state. The first thing that came to mind was to use a for loop on the string input and then whenever x is detected, I could split the string from that x to the end of the string and run one more loop to find the occurence of the underscores and use them to compute the noteLength value.

So then it would like

This is fine and it will get the job done. But I wanted to break away from the dependency on the for loop.

Enter String.replace

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.  The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.

Basically I d need to ‘match’ occurrences of  x followed by zero or more underscores and occurrences of hyphens. Then based on those, I d just need to push the desired object to an array.

And that’s about it. The jsperf for this shows tremendous performance improvement as well as reduced number of lines of code (from 25 lines it went down to 4 lines) without sacrificing readability!

Categories: Javascript | Tags: , | Leave a comment

How to load jquery plugins dynamically while understanding Javascript closures and the difference between apply and call.

I guess the issue for me is to keep things dynamic.
-Robert Downey, Jr.

When I was a kid, I had this big hard cover red book of Russian folk tales. This book was filled with stories of dragons with more than 8 heads dealing with sons and daughters of farmers while covering a lot of ground on foot or animal back. Each story had a really long title, just like the title for this blog post :)

At the cost of not digressing any more, I ll start off with what I intended to document through this post. I had to solve a challenge where there were over 50 custom jquery plugins written to do specific things on certain HTML elements but the presence of the HTML elements that they were to be initialized on were not fixed. It was certain though that there would not be more than 7 or 8 elements at any given time that would need their corresponding plugins. So here’s what I came up with for this. It also helps me showcase a really good example for JavaScript closure and the difference between apply and call. I ve noticed that these terms are searched widely and though the explanations for them exist widely too, there just arent enough good examples that demonstrate them.

Ok here goes.

You can download this sample from github to see how the files are structured and what are their contents.

Just as a sample, I created just 4 js files and called them a.js, b.js, c.js and d.js. These were to denote 4 custom jquery plugins. For this sample the plugin would just put the alphabet letter in the html() of the element they were initialized on. So the plugin a.js would insert ‘a’ in the html element that it was initialized on. b.js would insert ‘b’ in the html element that is was initialized and so on:

Then I created a HTML page that had DIVs in the following fashion in its BODY tag:

As you can see, each div has a class called ‘hasPlugin’ to denote that this html element will need a plugin initialized on it. These divs also have a data-plugin attribute that denotes the name of the plugin that it needs. As you can also see, I have 3 divs with the requirement for the plugin ‘a’. This is just to demonstrate a one to many relation while initializing the plugins.

The only next thing I did in the HTML was to add a script tag that pulled jquery from a CDN

This concludes my HTML setup. For the SCRIPT part, I started with an anonymous function declaration. But this is not my example for JavaScript closures. That example will come up shortly and it ‘will’ explain how and why you would use it :)

My goal was clear and my logic was simple. I knew that there could be multiple DIVs that required the same plugin. And I certainly did not want to go and fetch that plugin multiple times. Neither did I want to use some custom function to loop over an array to remove duplicate entries. So I defined a hash map kinda object called plugs = {}. I looped over the DIVs which had the class ‘hasPlugin’ and took their data-plugin attribute to determine the name of the required plugin. I started assigning the names of the plugins as properties of the plugs object. Every time I did that if that property already existed

This way I did not have to worry about having to explicitly remove duplicates. Here’s how that code looked:

At the end of that I got a pseudo hashmap with plugin names as the property name and an object with the DIVs that had the plugin applied to them as a value. I also included the name of the plugin in this object so that I could make use of it later.

All I need to do now was to go over the plugs object and take each ‘item’ in it and load the JavaScript file for it. On loading of that file I needed to initialize that plugin on to the DIVs of that ‘item’. Here’s where we’ll use the closure (as well as the function.call method)

A little bit of explanation is called for. In the loop, I m first setting up a file reference object that create’s a SCRIPT tag it’s src attribute set to the name of the plugin. That was pretty straightforward. The next thing I do is to check for the onload method of the file reference object in which I use a JavaScript closure. I love digressing and I m gonna do that for a bit now. Let’s say you had a bunch of buttons that you created from a ‘for’ loop. Like this:

What do you think will be alerted every time you click any of the buttons? If you are one of those really cool kids who actually try out things before answering these kinda questions, you ll take a moment to quickly run that last snippet in the console of your browser to learn that no matter what button you click, it always alerts 5! What a mischievous bunch of buttons we’ve created! :D Well maybe it was obvious and maybe you re so cool that you knew it without running the snippet in the console of your browser :)

If we change the snippet such that we use a JavaScript closure in the form of an anonymous function inside the loop and explicitly tell it the value of i then we can discipline the buttons to behave appropriately:

Basically we are passing that (function(){})(); thing inside the onclick to define an anonymous function which we are defining and calling at the same time. ()(); is the function call itself. The first set of braces is to define the function with whatever arguments we want. The second set of braces is to pass in the arguments we defined. This should suffice as a good example of a closure. If you run that last snippet in your browser’s console, you ll see that the buttons are not so mischievous anymore.

Going back to the intended subject of this post, we are using a similar closure to define an anonymous function which is called at the same time and we are passing it the plug object to work with.

Now we come to the difference between JavaScript function.call and function.apply. In the following partial snippet I m using function.call:

Both function.call and function.apply have a similar role to play. Both call a function and allow us to pass the value for ‘this’ as the first argument followed by the arguments required by the function itself. If you do not know how many arguments you are gonna end up passing OR if the function expected an Array to be passed, then use function.apply. But if you know the number of arguments you are going to pass, then use call. A comment on StackOverflow had an interesting way to remember this. The comment was something to the effect of, use Apply for an Array as an argument (AA) and use Call when you can Count the arguments you re going to pass (CC). Unfortunately (at least for me) this does not yet fully explain the difference nor the use case scenario for either function.apply OR function.call. I need a real world use case scenario sometimes to understand some concepts. The topic I m covering in this post helps me get just that. A use case scenario!

So as we ve discussed so far, we are dealing with a bunch of jquery custom plugins that we load dynamically and initialize them on DIV elements that need them. Since they are jquery plugins, they are basically namespaced under $.fn coz at the very basic level, a jquery plugin is:

So if I had to initialize that on the first DIV element on a page, I d first need to load the script file a.js along with jquery and then simply initialize the plugin in this way:

For our example, we do not have ‘div:first’ nor do we know that it needs plugin ‘a’. But we do have those in variables. So we use function.call in this fashion:

This will initialize the pluginName on to $(div). This could ve been done with function.apply in this fashion:

But since the plugin did not have any arguments for this sample, we do not need to pass any second argument to either call or apply. In such a case I d rather use function.call coz it may be a little faster than function.apply which has to parse the second argument as Array. Function.call is not obliged to do so and we do not have a second argument here.

So that summarizes my take on dynamic jquery plugin loading, closures and apply vs call. You can download this sample from github to see how the files are structured and what are their contents.

Categories: How To, Javascript, jQuery | Tags: , , , | Leave a comment

How to run Grunt tasks only on changed files

You can observe a lot by just watching.
-Yogi Berra

For a recent workflow improvement I was trying at work, I needed to setup a Grunt watch and uglify on a bunch of javascript files to minify them into individual minified files and then concatenate them. The number of files to be concatenated was over 50 hence uglifying the whole bunch each time a file was updated would slow down the workflow.

So the goal was to minify each file individually into its own minified version and then run a watch on the minified files directory contents and concatenate the minified files into one js file. The uglify target looked like this:

The second part of the goal was to concatenate minified files into one main.js. This needed to happen every time a file was minified. Which means I needed to run the uglify task only on the file that was changed or updated and then concatenate the minified files. Before moving on, here’s the Grunt concat task inside the watch:

A watch task on the ‘js’ directory would run the uglify task and a watch task on the ‘js-min’ directory would run the concat task. The challenge was, every time the uglify task ran, it went through all of the js files specified in it’s target and uglified them. And then the watch task on the ‘js-min’ directory would kick in and concatenate all the files in the ‘js-min’ directory. SO the required behaviour was to set the watch task for uglify to run only on the updated/changed file.

Say hello to the on watch event

Grunt watch has a ‘on’ event so that one can compile files as needed. My first hack was to use this ‘on’ event and run uglify on the changed file from this event’s handler which provides a filepath paramenter. Grunt’s core developers will not advise us to use this event method in this fashion as it deviates from the standard procedure of assigning tasks using Grunt. Hence we ll maintain the existing uglify task just the way it was defined earlier. In the watch event handler, we ll simply change our uglify task’s source parameter to the file that was updated. So instead of taking all the files defined in the src parameter, Grunt watch will only process the updated file

This will make sure that only the changed file is uglified. Once it compiles it as a minified file, we run concat on the minified files by adding another watch target in the Gruntfile.

This solution helps meet the goal I set out to achieve. Though there is an issue in this. What if we wanted to append .min.js to the end of all the files we minify? We could just add that in the uglify target object as ext: min.js. But then it will create some problems on files that have a dot (or 2) in their ‘name’ itself. For example its a common practice to name jquery plugins like this: jquery.pluginname.js

At the time of this writing, Grunt uglify will not differentiate between files with more than one dot in their name. It will use the first dot that it finds in the file name and consider the rest of the file path as an extension of the file. So let’s say we decide to append a .min.js to our uglified files, our Grunt task will convert both jquery.pluginname.js and jquery.js to jquery.min.js. This is not what we want! There is a bug filed for this and maybe the core team will do something to tackle it, but since one can pass a rename function, they may not consider tackling this right away.

A quick and dirty solution is to explicitly rename the changed files the way you want in the on watch event itself. So you’d first uncomment the ext portion in the uglify task and update the on watch task:

If you know a better way than this, then please do leave it in the comments.

Categories: How To, Javascript | Tags: , , | 1 comment

How to layout a BackboneJS project in CakePHP using GruntJS

BackboneJS does not seem to come with a recommended layout for its file structure, though Yeoman suggests it’s own concept of laying out a BackboneJS project. I took inspiration from Yeoman to put together this approach for laying out a BackboneJS project inside the CakePHP framework. CakePHP is convention over configuration and expects you to put all your assets inside cakeroot/app/webroot/.

For the sake of this tutorial, I m going to create my files based on a simple ToDo project since almost every developer creates a ToDo app at least once! The ToDo list app for this project has a database with 3 tables:

Inside webroot/js, create the following directories

Yeoman generates directories for routes, helpers and templates. I m not going to add these coz I dont need them. For routes, I m going to use only one file and it can stay inside the js folder alongside my main.js file. I have a feeling that the convention to use main.js comes from ActionScript 3.0 projects (though I do not have any proof of this)

Once you ve created your directories in the js folder, its time to put in some files. Here is the same directory structure for the js/ directory, but includes files that are based on my database schema.

Yeoman creates the main.js with one global variable based on the name of your project and creates placeholders within that for our models, collections, views and routes. Here s a sample of it:

Now, while defining your models or collections or views, make sure to namespace it inside ProjectName.Models or ProjectName.Collections or ProjectName.Views. For example, our task-model would look like this:

Notice the name of the model. The file was named task-model.js and the model itself is called TaskModel. This is just a convention. You can change this to whatever you think is better for you.

Finally templates, Yeoman does create a structure for that but I figured that out the easy way that it has not yet implemented the feature where you can define .ejs files inside your templates directory and use em from there. At least not as of this post. So instead of trying to do that, we can just define the templates inside a directory inside app/View/Elements/Templates. We can then render that element in Cake’s view file which also has the scripts pulled in for our app. For this tutorial, I have a controller called UsersController.php and I have routed /app to UsersControllers:app

Since that s how the route is defined, we need to have a file at app/View/User/app.ctp. At the beginning of this render the templates file and at the end of the same file, pull in the required JS files.

For now I ll just pull all the required JS files from CakePHP’s perspective (later we’ll use Grunt):

Lets say your application-router.js file looks like this:

Then at the end of all the javascript calls, create script tag and create a router object and kick start the show!

We could even use GruntJS and have all the JavaScript and CSS files uglified or minified into one single app.js and app.css file and just pull that instead. To do so you ll need NodeJS and Node Package Manager installed. If you do have these installed, then create a file called package.json inside cakeroot/app/. I m not using the webroot directory coz I dont want my Gruntfile and package.json file to be publicly accessible. Inside your package.json file you could do something like this:

Then, add n navigate to your app folder in a terminal and run:
npm install

Once the required modules are installed, you can add app/node_modules to your .gitignore file. Then create a file (inside app/) called Gruntfile.js (unless it is not already created) and enter something like this:

I m just using uglify and cssmin along with watch. You can add whatever else you may need. After that you wont need to pull all those JS files in your view file. As you may already know, the browser pulls 2 files at a time from the server. So if you have 16 files (including Javascript as well as CSS), then it ll make 8 trips to the server and back!

Now that we have some grunt tasks running, we can reduce the round trips to the server (and cut file size considerably). Run ‘grunt’ from the ‘app/’ directory in a terminal and marvel at the ‘magic’ from the contributors of Grunt as you make even the tiniest of the changes to the files that are being ‘watched’. These views are just my idea based on how Yeoman lays out a Backbone JS project. If you have some suggestions to improve this, then please do share.

Categories: How To, Javascript | Tags: , , , | 3 comments

Install Apache, MySQL PHP and phpMyAdmin on Ubuntu 13.04 Raring Ringtail

When Thomas Edison worked late into the night on the electric light, he had to do it by a gas LAMP or candle. I’m sure it made the work seem that much more urgent.
-George Carlin

Ubuntu 13.04 ‘Raring Ringtail’ released yesterday and though I use Crunchbang, like any ex Ubuntu fanboy I got myself the iso, put it on a thumbdrive and installed it on a small netbook I have that was just lying around doing nothing fancy. I thought I d install the new Ubuntu on it and use it to ‘code’ while in the John or while standing in the line at Starbucks :D

So anyway, I had to setup a LAMP server:




Restart Apache


I don’t like to use Apache’s default http folder /var/www so I need to update the apache2.conf file:

Changing the default location will require me to make sure phpMyAdmin continues to load on http://localhost/phpMyAdmin so at the end of the same file I ll add the virtual host configuration for phpMyAdmin

Restart Apache

Categories: How To, Linux, Useful | 29 comments

Rearrange characters of a string to create all possible combinations

Governments tend not to solve problems, only rearrange them
-Ronald Reagan

How to take a word(string) and rearrange its letters to create all possible combinations? Lets say we want to use the word ‘goal’ and list out all possible words that can be made by rearranging the letters of the word ‘goal’. Take the first letter ‘g‘ and then create permutations and combinations of the balance letters ‘oal‘ and append them to ‘g‘.

g oal

Then take go and create create permutations for the balance letters ’al‘ and append them to ‘go‘.

go al

Then we take goa and l

goa l

This is done for each of the letters. As you can see, with each letter, the permutations will reduce for the subsequent letters. The parameters that are passed to our recursive function are a prefix that will be used to prepend (starting with an empty string) AND the balance letters of the word.

Here’s the function in JavaScript:

Categories: How To, Javascript | 1 comment

wGet it all

The first step to getting the things you want out of life is this: Decide what you want.
- Ben Stein

wget it all
For a music related project I m working on, I needed sound files for a chromatic scale. I found a site that had the files I needed but they weren’t listed anywhere with their links. They were mp3 links to play buttons at various places in the site. I found that the format of the file names was B3, Bs3, C3, Cs3 etc… the ‘s’ meant ‘sharp’ and the number was the octave. I needed sound files from the third octave so here s what I did and downloaded the one’s I need without individually right clicking on each of the play buttons and selecting to download the link to a specific location on my computer.

I created a file called ‘download-script’ (without any extension) to write a shell script for this and defined a variable for the URL and a space separated list for the file names :

wget is a command line utility to download files from a FTP or a HTTP server. In the loop I m using -O (output document option) so that the downloaded file would have the name in the format I need (e.g. C3.mp3) and not in the naming format on the website (some-prefix.net_C3.mp3). Then I made the file executable

And simply called it from the terminal

Voila! All files downloaded :)

Categories: How To, Linux | Leave a comment

← Older posts