Introduction
Code formatting is an essential part of modern development workflows. Consistent code style improves readability, reduces cognitive load, and helps teams collaborate more effectively. While many developers use local formatting tools, a dedicated formatting service can provide consistent results across different environments and platforms.
In this tutorial, we'll build a code formatting microservice using Node.js, Express, and Prettier. This service will expose REST API endpoints that accept code in various languages and return the formatted version according to configurable rules.
Prerequisites
Before we begin, make sure you have the following installed:
- Node.js (v14 or later)
- npm or yarn
- Basic knowledge of JavaScript and REST APIs
- A code editor (VS Code recommended)
Project Setup
Let's start by creating a new directory for our project and initializing it:
mkdir prettier-api-service
cd prettier-api-service
npm init -y
This will create a basic package.json
file. Let's modify
it to include some additional information and scripts:
{
"name": "prettier-api-service",
"version": "1.0.0",
"description": "A code formatting microservice using Express and Prettier",
"main": "src/index.js",
"type": "module",
"scripts": {
"start": "node src/index.js",
"dev": "nodemon src/index.js",
"test": "jest"
},
"keywords": [
"prettier",
"formatting",
"api",
"express",
"microservice"
],
"author": "Your Name",
"license": "MIT"
}
Note that we're using ES modules ("type": "module"
) for
this project, which allows us to use modern import/export syntax.
Installing Dependencies
Now, let's install the necessary dependencies:
npm install express cors helmet prettier @prettier/plugin-babel @prettier/plugin-php prettier-plugin-go prettier-plugin-java prettier-plugin-ruby prettier-plugin-solidity
npm install --save-dev nodemon jest supertest
Here's what each package does:
- express: Web framework for Node.js
- cors: Middleware to enable CORS
- helmet: Middleware to secure Express apps
- prettier: The core formatting engine
- @prettier/plugin-*: Plugins for various languages
- nodemon: Development tool for auto-restarting the server
- jest and supertest: Testing libraries
Creating the Express Server
Let's create the basic structure for our Express server. First, create
a src
directory and an index.js
file inside
it: