Home >Web Front-end >JS Tutorial >Building a Microblog Using Node.js, Git and Markdown
Build a microblog based on Node.js, Git and Markdown
This article explores how to build a microblog using Node.js, Git, and a few dependencies. This app is designed to serve static content from files submitted to the repository. You will learn how to build and test your application and gain insight into the process of delivering your solution. Ultimately, you'll have a minimalist, runnable blog application that you can build on.
Key points:
Main components of microblogs
To build a great blog, first of all, you need some components:
To send HTTP messages, I chose Node.js because it provides everything you need to send a hypertext message from the server. The two modules of particular interest are http
and fs
. The http
module will create a Node HTTP server. The fs
module will read the file. Node has a library for building microblogs using HTTP.
To store a blog post repository, I will choose Git instead of a fully functional database. The reason is that Git itself is a version-controlled text document repository. This is exactly everything I need to store blog post data. Getting rid of adding databases as dependencies prevented me from having to write code for a lot of problems.
I chose to store blog posts in the Markdown format and parse them using marked
. If I decide to do this later, this will allow me to be free to gradually enhance the original content. Markdown is a good lightweight alternative to regular HTML.
For unit testing, I chose the excellent test runner roast.it. I chose this alternative because it has no dependencies and it satisfies my unit testing needs. You can choose another test runner like tape, but it has about eight dependencies. The reason I like roast.it is that it has no dependencies.
With this list of components, I have all the dependencies I need to build a microblog.
Selecting dependencies is not easy. I think the key is that anything beyond the scope of the current problem can become a dependency. For example, I don't build a test runner or data repository, so I add it to the list. No given dependency can swallow the solution and hijack the code. Therefore, it makes sense to select only lightweight components.
This article assumes that you are already familiar with Node, npm, and Git, as well as various testing methods. I don't go through each step of building a microblog step by step, but focus on specific areas of the code. If you want to follow the action at home and the code has been uploaded to GitHub, you can try each code snippet.
Test
Testing gives you confidence in your code and strengthens the feedback loop. A feedback loop in programming refers to the time it takes between writing any new code and running it. In any web solution, this means skipping many layers to get any feedback. For example, browsers, web servers, and even databases. As complexity increases, this can mean that it takes several minutes or even an hour to get feedback. Using unit testing, we can reduce these layers and get quick feedback. This puts the focus on the current issue.
I like to start any solution by writing fast unit tests. This got me started writing tests for any new code. This is how you start running using roast.it.
Add to the package.json
file:
<code class="language-json">"scripts": { "test": "node test/test.js" }, "devDependencies": { "roast.it": "1.0.4" }</code>
test.js
Files are where you introduce all unit tests and run them. For example, you can do the following:
<code class="language-javascript">var roast = require('roast.it'); roast.it('Is array empty', function isArrayEmpty() { var mock = []; return mock.length === 0; }); roast.run(); roast.exit();</code>
To run the test, execute npm install && npm test
. To my pleasure, I no longer have to work hard to test new code. This is what testing is about: Happy programmers gain confidence and focus on solutions.
Skeleton
The microblog will use Node to respond to client requests. An effective way is through the http.CreateServer()
Node API. This can be seen in the following excerpts in app.js
:
<code class="language-javascript">/* app.js */ var http = require('http'); var port = process.env.port || 1337; var app = http.createServer(function requestListener(req, res) { res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8'}); res.end('A simple micro blog website with no frills nor nonsense.'); }); app.listen(port); console.log('Listening on http://localhost:' + port);</code>
Run this script through the npm script in package.json
:
<code class="language-json">"scripts": { "start": "node app.js" }</code>
Now, http://localhost:1337/
becomes the default route and returns a message to the client. The idea is to add more routes to return other responses, such as responding with blog post content.
Folder structure
To build the structure of the application, I decided to use the following main parts:
I will use these folders to organize the code. Here is an overview of the purpose of each folder:
blog
: Store original blog posts in pure Markdown format message
: Reusable module for building response messages to clientsroute
: Routes other than default routestest
: Where to write unit testsview
: Where to place HTML templatesMore routing and testing
For the first use case, I will introduce another route to the blog post. I chose to put it in a testable component called BlogRoute
. What I like is that you can inject dependencies into it. This separation of concerns between units and their dependencies makes unit testing possible. Each dependency gets a mock in the isolated test. This allows you to write immutable, repeatable, and fast tests.
For example, the constructor looks like this:
<code class="language-json">"scripts": { "test": "node test/test.js" }, "devDependencies": { "roast.it": "1.0.4" }</code>
Effective unit tests are:
<code class="language-javascript">var roast = require('roast.it'); roast.it('Is array empty', function isArrayEmpty() { var mock = []; return mock.length === 0; }); roast.run(); roast.exit();</code>
Currently, BlogRoute
expects a req
object that comes from the Node API. To get the test passed, just do the following:
<code class="language-javascript">/* app.js */ var http = require('http'); var port = process.env.port || 1337; var app = http.createServer(function requestListener(req, res) { res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8'}); res.end('A simple micro blog website with no frills nor nonsense.'); }); app.listen(port); console.log('Listening on http://localhost:' + port);</code>
With this we can connect it to the request pipeline. You can do the following in app.js
:
<code class="language-json">"scripts": { "start": "node app.js" }</code>
The advantage of having testing is that I don't have to worry about implementation details in advance. I'll define message
soon. The res
and req
objects are from the http.createServer()
Node API.
Repository
The next problem to be solved is to read the original blog post data in BlogRoute.route()
. Node provides a fs
module that you can use to read from the file system.
Example:
<code class="language-javascript">/* route/blogRoute.js */ var BlogRoute = function BlogRoute(context) { this.req = context.req; };</code>
This code snippet is located in message/readTextFile.js
. At the heart of the solution, you read text files in the repository. Please note that fs.readFile()
is an asynchronous operation. That's why it takes the fn
callback and calls it with file data. This asynchronous solution uses simple callbacks.
This provides the requirement for file IO. What I like about it is that it only solves one problem. Since this is a cross-domain issue, such as reading files, there is no need to do unit testing. Unit testing should only test the isolation of your own code, not others' code.
In theory, you can simulate a file system in memory and write unit tests in this way, but the solution will then start leaking concerns everywhere and turning into confusion.
Cross-domain issues such as reading files are beyond the scope of the code. For example, reading files depends on a subsystem that you cannot directly control. This makes the tests fragile and increases the time and complexity of the feedback loop. This is a problem that must be separated from your solution.
Markdown parser
The next problem is to convert the original Markdown data from the repository to HTML. This process is divided into two steps:
view
folder In sound programming, the idea is to break down a big problem into small, easy-to-handle parts. Let's solve the first question: How to get HTML templates based on what I'm in BlogRoute
?
One method might be:
<code class="language-javascript">/* test/blogRouteTest.js */ roast.it('Is valid blog route', function isValidBlogRoute() { var req = { method: 'GET', url: 'http://localhost/blog/a-simple-test' }; var route = new BlogRoute({ req: req }); return route.isValidRoute(); });</code>
Remember that this will replace the virtual callback used in the previous section, called dummyTest
.
To replace the callback dummyTest
, do the following:
<code class="language-json">"scripts": { "test": "node test/test.js" }, "devDependencies": { "roast.it": "1.0.4" }</code>
(The subsequent content is omitted due to space limitations, please add it yourself as needed)
The above is the detailed content of Building a Microblog Using Node.js, Git and Markdown. For more information, please follow other related articles on the PHP Chinese website!