Setting up Last.fm Feed with Node

Don't make me wait for you self-absorbed crap.

I wanted to pull my Last.fm Recently Played list directly from the Last.fm API and display it as an aside on this site. To do this I wanted to use a node package, if possible. Luckily there is a simple one that was created a few years back I found on NPM and GitHub

I used npm to install the package:

npm install lastfm-node

I wanted to build a route that automatically ran the API calls and cached the return from Last.fm (on some time based cache) and then use a jQuery AJAX request to pull the data after the page was displayed for the user. No one should wait for your Last.fm feed (or Twitter or any other self-involved content) for the real content.

To do this I created a new Last.fm route that would return my latest listens in a format I wanted as JSON. I created a new route as per standard Express:

exports.lastfm_feed = function (req, res){
    lastfm.request('user.getRecentTracks', {
        user: 'ppjim3',
        limit: 20,
        handlers: {
            success: function(data) {

                var recent_tracks = data.recenttracks.track
                    , track_strings = [];

                for (var i = recent_tracks.length - 1; i >= 0; i--) {
                                        track_strings.push(recent_tracks[i].artist['#text'] + ' - ' + recent_tracks[i].name);
                }

                // Save the returned data to the cache object
                                    res.json(track_strings, { 'Content-Type': 'text/javascript' });
            },
            error: function(err) {
                throw err;
            }
        }
    });
};

I then used the Last.FM package to make a request and pull the results I was after.