Following Ricky’s request from the comments, now I have a little demo showing how to consume data from a MySQL DB. This time I am not using express to avoid the amount of dependencies and focus on the actual test (Even there I can’t keep myself 100% focused on MySQL example cause I am a big enemy of nested callbacks).
The example is using Q to “synchronize” the initialization of MySQL connection and the HTTP server so we have both dependencies correctly initialized when we receive requests from the clients (browser). You will need to change the values to connect to your database.
1 2 3
Q is used to provide the promises API. It aids on controlling the application flow with asynchronous methods.
MySQL is self explanatory.
HTTP is used to provide the demo an entry point to our clients. Since this is only a basic demo I am not using other frameworks. If you plan to do your production application then you must consider using a proper framework like Express.
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
In startDb the connection to MySQL is triggered. The method will immediately return a deferred promise so any interested will be able to subscribe to either the resolve or reject result by using PromiseJS API methods like then. Promises are not strictly necessary but in my opinion are a good practice to keep the code both clean and readable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
If you already did at least the first NodeJS code example on its page, the above example will be familiar; I can only take credit for using Promises to notify instead of a module variable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
Now that we have our DB Connection and the HTTP server waiting for connections, let’s do something. On ready method it is defined an event listener that will receive all the requests on the server, on port 3001, it will perform a query, and finally respond to the server with the result of the query.
Last but not least, here is our demo instance that will start everything automatically.
An example of the output of this demo:
1 2 3 4 5 6 7 8 9 10 11
You can get the full source code from this Git Repository. Once you have it, do not forget to do “npm install” on the project folder to grab all the node dependencies.
Leave your questions and comments and I’ll be more than happy to
troll help you :D !