Node.js – a quick start file upload guide, Part 1

I’ve talked on here before about using Node’s NPM package manager to get started with Gulp for some lovely workflow simplifications (oh, how I love Gulp!) but that’s all I’ve really been using it for until now. Node itself is one of those things I’ve never really a) had time to properly learn and b) had a chance to actually implement in a real world project. But all that’s changed and I want to talk you through my first Node.js app – an easy to implement file uploader!

A little bit of history – one of the projects I’m working on a the moment is going to require a constant uploading of csv files to a server so that they can be batched into a database for use in Microsofts Power BI; that’s something I’m going to be talking more about in the future. The actual file upload script I’d written as a PHP app, fairly straightforward but a little bloated for what it does. I wanted something a little simpler and more lightweight so I looked to Node.js. I’ll be honest, I pinged back and forth for a few weeks trying to figure out how to get things working.

Node seems like a great framework – a way of running Javascript server side to do non cpu intensive tasks like running simple apps or sites, but a lot of the tutorials and examples I was looking at to get started were either too vague or assumed a basic knowledge that I didn’t really have yet. Then I found this one by Shiya Luo: http://shiya.io/simple-file-upload-with-express-js-and-formidable-in-node-js/. As always, credit where credit is due, that tutorial is one of the best I’ve found to see Node working in an easy to understand, applied manner. It forms the basis of everything going forward and gave me a good understanding of how I could build my basic web app in Node and get it running to handle the file upload. It also covers some fundamentals in that will be handy for future projects. So, as with my Gulp posts, I’m going to break the process down and expand on it so that we can see how every step slots together. This is very much to help my understanding as well as providing others with a helpful guide.

NOTE: As I was writing this it all got a bit… long! So, I decided to split the post down into a number of parts. This is part 1, which will cover the basics of using Node to serve HTML pages. I’ll be posting part 2, which will cover forms and files, tomorrow, so please check back!

Let’s go!

Step 1: Install Node.js

I mean, only if you haven’t already. Hit up http://nodejs.org and grab the required version for your OS.

Step 2: Set up your project

Okay, let’s get our hands dirty. Fire up your favourite command prompt and get tippity-typing. First off go to your preferred location for web projects. I keep everything I work on in my apache www folder, because… well, because. It keeps everything in one place. I’m sure there is a better approach but that’s another article for another time! 🙂

Here’s my commands – you can change yours up as you need to:

cd c:\wamp64\www\
mkdir nodejs-file-upload

Now head into your project folder and initiate Node with:

npm init

This will create your package file that will hold all the information about the packages you’re using in your project so you can easily set it up again in the future. For reference, I used the entry point app.js (in all honesty I’m still really figuring out what the init set up does – I’ll research that more in the future!)

Step 3: Install Express

Okay, so first off we’re going to code a simple node project that will display a HTML page. Node runs its own servers per project and there seems to be a number of ways you can spin one up but, as per the tutorial I linked to we’re going to be using the Express package, which provides an application framework. You can find more about that here: https://expressjs.com/

First off, let’s install the package in our project with:

npm install --save express

The –save extension will make sure that a reference to the installed package is saved in your package.json file as a dependency for your project. Apparently this is no longer needed in Node v.5 onwards so you may or may not want to use it.

Step 4: Build a page and spin up a server

Right, crack open your favourite editor (mine’s VS Studio, and you can read why here) and pull up your project folder. Let’s make ourselves a simple html page.

Create a page called index.html and pop the following code in it. We’re using the Bootstrap CDN because Bootstrap is awesome and instantly makes anything look nice:

NOTE: So, WordPress.com was being throroughly idiotic with embedding the HTML using code and pre. Some of the stuff was still rendering for some reason! I’ve created a Google Doc to accompany this post with the relevant code in it. You can get hold of that here: https://docs.google.com/document/d/1O5BmqFcJyFRaZytLYV_SqiA1teV8p6UjP8L84o9oRdM/edit?usp=sharing

For reference, I use a VS Studio extension called Bootstrap 4 CDN Snippet that lets me quickly scaffold Bootstrap HTML pages by entering !bcdn into my editor.

Okay, now we’ve got our HTML, let’s code the “doing” stuff to get it showing in a browser. Create a file called app.js and fire it up in your editor. First off, we’re going to make sure that Express is loaded in:

var express = require(‘express’);
var app = express();

That loads our Express package and sets an object called app to be an Express object. That will handle all our server related stuff.

For our basic app we need to define a route on the… root… That’s the base URL that we’ll hit up to load the app. Let’s get that in with:

app.get('/', function (req, res){
   res.sendFile(__dirname + '/index.html');
});

So that is saying, when app receives a get request on /, serve up the index.html page to the browser. Simple. Although, at the moment, it’s not going to do a huge amount. We need to set up our server so that app will be listening for requests. That’s also simple, thankfully! Add another variable declaration first:

var port = 3000

And then tell app to listen on that port:

app.listen(port, () => console.log(`App listening on port ${port}`))

The console log part gives us a nice bit of feedback in our console to show that the app is working as expected. So let’s do that! Head back to your terminal and run the app with:

node app.js

You should see the message – App listening on port 3000. Open up a new tab in your browser and head to http://127.0.0.1:3000 to see your index page! Wasn’t that easy?

Step 5: A bit more routing

This step is kind of optional but will demonstrate a bit more about routing. Stop your app by hitting ctrl+c in your terminal.

We’re going to set up another html page, so create one and call it about.html. Here’s the code:

NOTE:  Once again, you can find the HTML for this example here: 
https://docs.google.com/document/d/1O5BmqFcJyFRaZytLYV_SqiA1teV8p6UjP8L84o9oRdM/edit?usp=sharing

And add the following route to your app.js:

app.get('/about', function (req, res){
   res.sendFile(__dirname + '/about.html');
});

Run your app again from your terminal and head to http://127.0.0.1:3000/about in your browser. Voila! Your about page will now be displayed. Good, innit?

So, you should now have two html files and an app.js file that looks like this (I’ve added in some comments for readability):

var express = require('express');
var app = express();
var port = 3000;

//Routes
app.get('/', function (req, res){
   res.sendFile(__dirname + '/index.html');
});
app.get('/about', function (req, res){
   res.sendFile(__dirname + '/about.html');
});

//Listen
app.listen(port, () => console.log(`App listening on port ${port}`))

Further reading

So, this is the end of part 1. Check back tomorrow when we’ll look at putting in our upload form and handling the upload as it hits our server.

For now, though, there’s some further reading that I (and indeed you) will be going off to do. Obviously setting up flat HTML pages with full scaffolding every time is going to be a chore, so there has to be some kind of templating that we could put in. I think there’s also potential here to look into how we could take the routing further to deliver more dynamic content in our Node sites. Finally, you could also add in some nice Bootstrap menus to guide your users about your nice new Node powered site!

That’s all for the future, though – join me tomorrow for part 2! And don’t forget, if this has been useful, hit up the comments below!


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s