Home Web Front-end JS Tutorial Building a Microblog Using Node.js, Git and Markdown

Building a Microblog Using Node.js, Git and Markdown

Feb 17, 2025 am 10:48 AM

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.

Building a Microblog Using Node.js, Git and Markdown

Key points:

  • Node.js provides a balanced set of APIs that are ideal for building microblog platforms that do not require unnecessary complexity.
  • Git is used to store blog posts as versioned text documents without using traditional databases.
  • Markdown is used for blog post formatting, allowing for lightweight content and can be gradually enhanced.
  • Roast.it is used for unit testing because it is simple and has no dependencies, allowing for quick feedback and enhanced developer confidence.
  • The microblog architecture is designed around simplicity, with routing and minimal dependencies for providing blog content, ensuring fast performance.
  • The application uses a custom Markdown parser and simple template functions to convert Markdown to HTML, ensuring that the blog is lightweight and responsive.

Main components of microblogs

To build a great blog, first of all, you need some components:

  • Library for sending HTTP messages
  • Repository for storing blog posts
  • Unit Test Runner or Library
  • Markdown parser

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:

"scripts": {
  "test": "node test/test.js"
},
"devDependencies": {
  "roast.it": "1.0.4"
}
Copy after login
Copy after login
Copy after login

test.js Files are where you introduce all unit tests and run them. For example, you can do the following:

var roast = require('roast.it');

roast.it('Is array empty', function isArrayEmpty() {
  var mock = [];

  return mock.length === 0;
});

roast.run();
roast.exit();
Copy after login
Copy after login

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:

/* 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);
Copy after login
Copy after login

Run this script through the npm script in package.json:

"scripts": {
  "start": "node app.js"
}
Copy after login
Copy after login

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:

Building a Microblog Using Node.js, Git and Markdown

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 clients
  • route: Routes other than default routes
  • test: Where to write unit tests
  • view: Where to place HTML templates

More 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:

"scripts": {
  "test": "node test/test.js"
},
"devDependencies": {
  "roast.it": "1.0.4"
}
Copy after login
Copy after login
Copy after login

Effective unit tests are:

var roast = require('roast.it');

roast.it('Is array empty', function isArrayEmpty() {
  var mock = [];

  return mock.length === 0;
});

roast.run();
roast.exit();
Copy after login
Copy after login

Currently, BlogRoute expects a req object that comes from the Node API. To get the test passed, just do the following:

/* 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);
Copy after login
Copy after login

With this we can connect it to the request pipeline. You can do the following in app.js:

"scripts": {
  "start": "node app.js"
}
Copy after login
Copy after login

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:

/* route/blogRoute.js */
var BlogRoute = function BlogRoute(context) {
  this.req = context.req;
};
Copy after login

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:

  • Get HTML template from view folder
  • Parse Markdown to HTML and fill in templates

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:

/* 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();
});
Copy after login

Remember that this will replace the virtual callback used in the previous section, called dummyTest.

To replace the callback dummyTest, do the following:

"scripts": {
  "test": "node test/test.js"
},
"devDependencies": {
  "roast.it": "1.0.4"
}
Copy after login
Copy after login
Copy after login

(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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Zustand asynchronous operation: How to ensure the latest state obtained by useStore? Zustand asynchronous operation: How to ensure the latest state obtained by useStore? Apr 04, 2025 pm 02:09 PM

Data update problems in zustand asynchronous operations. When using the zustand state management library, you often encounter the problem of data updates that cause asynchronous operations to be untimely. �...

See all articles