Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Merge branch 'master' of github.com:creationix/howtonode.org

  • Loading branch information...
commit bd8573a05d9b6301d5ff2890142c50c7390ad468 2 parents 5c42590 + 639cc13
Tim Caswell authored
View
2  .gitignore
@@ -1,2 +1,4 @@
cache
node_modules
+*.iml
+.idea
View
94 articles/node-js-and-mongodb-getting-started-with-mongojs.markdown
@@ -0,0 +1,94 @@
+Title: Node.js and MongoDB - Getting started with MongoJS
+Author: Srirangan
+Date: Mon Feb 06 2012 21:15:00 GMT+0530 (IST)
+Node: v0.6.10
+
+It won't be an exaggeration if one claims that in the past few months Node.js and MongoDB have literally taken the
+software and web industries by storm.
+
+Not just bleeding-edge startups but even medium and large enterprises are leveraging these two technologies to deliver
+a better experience to their users by build more capable, performant and scalable apps.
+
+So what is Node.js?
+
+ Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications.
+ Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for
+ data-intensive real-time applications that run across distributed devices.
+
+..and what is MongoDB?
+
+ MongoDB is a scalable, high-performance, open source NoSQL database.
+
+This post will cover the basics and get you started with your Node.js + MongoDB app. Make sure you have Node.js
+installed and MongoDB setup on your developer machine.
+
+Let's verify your Node.js installation and start the MongoDB server:
+
+ $ node -v
+ $ mongod
+
+### Introducing MongoJS
+MongoJS is a brilliant little Node.js package that lets you access MongoDB using an API that is extremely similar to
+MongoDB's JavaScript shell.
+
+### Installing MongoJS
+Once Node.js has been setup correctly on your machine, you can use its internal package manager NPM to install MongoJS:
+
+ $ npm install mongojs
+
+We can now start building our JavaScript application and connect to our MongoDB server:
+
+ // app.js
+ var databaseUrl = "mydb"; // "username:password@example.com/mydb"
+ var collections = ["users", "reports"]
+ var db = require("mongojs").connect(databaseUrl, collections);
+
+The databaseUrl can contain the database server host and port along with the database name to connect to. By default
+the host is “localhost” and the port is “27017“. If you're using the default, which is likely on a developer
+environment, the databaseUrl can contain just the actual database name for our app.
+
+The collections is a set (array) of collections our application uses. It isn't mandatory but is preferred as it allows
+us to emulate a MongoDB JavaScript client like API within our Node.js app.
+
+Here's an example for finding documents within a collection specifically in this case to find all female users.
+
+ // app.js
+ db.users.find({sex: "female"}, function(err, users) {
+ if( err || !users) console.log("No female users found");
+ else users.forEach( function(femaleUser) {
+ console.log(femaleUser);
+ } );
+ });
+
+Notice how our initial query is a near duplication of the corresponding query in MongoDB's console. In addition to the
+query, in our Node.js source code (i.e. app.js) we pass a callback function to handle the results of the query.
+
+Node.js implements an event based concurrency paradigm and almost everything is always a callback. This allows your
+Node.js app to be non-blocking and high performing.
+
+What happens in our specific callback is self-explanatory — we check for errors and results, and if the query returns
+female users they are logged to the console.
+
+Okay, how do I save a new user in my collection? Exactly how you would do it in the console, your code will look like
+this:
+
+ // app.js
+ db.users.save({email: "srirangan@gmail.com", password: "iLoveMongo", sex: "male"}, function(err, saved) {
+ if( err || !saved ) console.log("User not saved");
+ else console.log("User saved");
+ });
+
+Here's an example for updating a record / document:
+
+ // app.js
+ db.users.update({email: "srirangan@gmail.com"}, {$set: {password: "iReallyLoveMongo"}}, function(err, updated) {
+ if( err || !updated ) console.log("User not updated");
+ else console.log("User updated");
+ });
+
+Okay, now we run this app in the console:
+
+ $ node app.js
+
+And there we have it, an incredibly simple quick start for Node.js + MongoDB enthusiasts. Happy coding!
+
View
86 articles/really-simple-file-uploads.markdown
@@ -0,0 +1,86 @@
+Title: Really simple file uploads with Express
+Author: Srirangan
+Date: Sun Feb 05 2012 11:00:00 GMT+0530 (IST)
+Node: v0.6.10
+
+Few days ago I was working on a fairly typical web application and I faced the challenge of implementing a fairly
+typical web application feature - file uploads. It was the first time I was implementing file uploads with Node (and
+Express) and I did what anyone else would do - I googled it.
+
+Unfortunately all the articles / posts out there are either outdated, too complex or plain wrong. So I did the next
+most obvious thing - post a question on the mailing list. As always Mr. Holowaychuk was incredibly quick to respond.
+His answer lead me to do what I should have done in the first place - read the docs.
+
+### The upload form
+This is the most obvious part of the challenge. You're probably familiar with this already. Anyway, for the sake of
+completeness of this article, here it is.
+
+You will need a form in your browser for the file upload. I use Jade to generate my HTML and here how it looks:
+
+ form(action="...", method="post", enctype="multipart/form-data")
+ input(type="file", name="displayImage")
+
+The *form.action* will point to a route that handles the file upload. More below.
+
+### Accessing the uploaded file
+If you're using recents versions of Node and Express, file uploads are a piece of cake. And I'll back this claim but
+before we go any further make sure you're familiar with [routes, requests and responses in Express](http://expressjs.com/guide.html).
+
+Okay, now let's justify the "piece of cake" claim. In our file upload route, the *req* parameter has *req.files*
+available. Here's an example of what the *req.files* would contain:
+
+ {
+ displayImage: {
+ size: 11885,
+ path: '/tmp/1574bb60b4f7e0211fd9ab48f932f3ab',
+ name: 'avatar.png',
+ type: 'image/png',
+ lastModifiedDate: Sun, 05 Feb 2012 05:31:09 GMT,
+ _writeStream: {
+ path: '/tmp/1574bb60b4f7e0211fd9ab48f932f3ab',
+ fd: 14,
+ writable: false,
+ flags: 'w',
+ encoding: 'binary',
+ mode: 438,
+ bytesWritten: 11885,
+ busy: false,
+ _queue: [],
+ drainable: true
+ },
+ length: [Getter],
+ filename: [Getter],
+ mime: [Getter]
+ }
+ }
+
+In the *req.files* object above, the property *displayImage* is the name of the file field in your HTML form and
+*req.files* will contain one property each for every valid HTML file form field.
+
+The file object contains the *type*, *size* and *name* properties for your server side validations.
+
+### Saving the uploaded file
+
+Assuming the file is valid, you use the *path* property for the next step. The *path* would typically contain a location
+in the *tmp* folder. Your application logic could either require you to access the contents of the file or simply move
+the uploaded file to another location.
+
+ fs.readFile(req.files.displayImage.path, function (err, data) {
+ // ...
+ var newPath = __dirname + "/uploads/uploadedFileName";
+ fs.writeFile(newPath, data, function (err) {
+ res.redirect("back");
+ });
+ });
+
+In the *fs.readFile* callback, we have the *data* parameter through which we can access the contents of the file. The
+example above is taken from an application that needed to modify the file and save it in a new location. Thus
+*fs.writeFile* is used to write *data* to the *newPath*.
+
+If your app needs to simply move the uploaded file without modifying the contents *fs.rename* can be used as more
+simpler option.
+
+---
+
+That's all there is to it. I've done file uploads in many server side languages including Python, Java, Scala and PHP
+and I don't think its ever been this simple. So much for JavaScript being labeled as an inferior server side language.
View
20 authors/Srirangan.markdown
@@ -0,0 +1,20 @@
+Github: Srirangan
+Email: srirangan@gmail.com
+Homepage: http://srirangan.net
+Twitter: srirangan
+
+I'm a passionate programmer and product developer. I've been programming professionally since 2002 and I bring expertise in both front-end and back-end development.
+
+In the last ten years, I've successfully executed freelance, open source and enterprise projects. I have been part of cross-functional and cross-cultural teams and I've had the opportunity to [work](http://www.linkedin.com/in/srirangan) with some very interesting people and companies.
+
+I enjoy building browser based, real-time apps using innovative technologies including Node.js, Socket.io, Express.js, HTML5, JQuery, SugarJS, CSS3 etc.
+
+Enterprise technologies that interest me are primarily Python and Scala. I've been working with NoSQL databases — MongoDB and Google Data Store APIs in particular.
+
+Other technologies that I've had fun with over the years are Adobe Flex, Java (Spring, Hibernate and popular enterprise frameworks), PHP 5 and related platforms, frameworks and libraries.
+
+I'm the creator of [Review19](http://www.review19.com) - next generation, real-time collaboration.
+
+I'm a keen open-source enthusiast and my [GitHub](https://github.com/Srirangan) profile contains contributions to various Node.js, Scala, Python and Adobe Flex projects.
+
+I'm the author of the [Apache Maven 3 Cookbook](http://www.packtpub.com/apache-maven-3-0-cookbook/book) (Packt Publishing, ISBN 978-1-849512-442) which is available for purchase in stores and on Barnes and Nobles, Amazon and Flipkart.
Please sign in to comment.
Something went wrong with that request. Please try again.