Let's create a step-by-step guide to build a simple Markdown editor using Node.js, Express, and a front-end library like marked
for rendering markdown content.
Step 1: Set Up Your Project
Create a new project folder:
mkdir markdown-editor cd markdown-editor
Initialize a new Node.js project:
npm init -y
Install necessary dependencies:
npm install express ejs marked
Step 2: Create Your Folder Structure
Create the following folder structure:
markdown-editor/
|-- public/
| |-- styles/
| |-- main.css
|-- src/
| |-- routes/
| |-- index.js
| |-- app.js
|-- views/
| |-- index.ejs
|-- server.js
Step 3: Set Up Express Server
In app.js
, set up a basic Express server and middleware:
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.static('public'));
app.set('view engine', 'ejs');
// Set up routes
const indexRoutes = require('./routes/index');
app.use('/', indexRoutes);
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Step 4: Create Routes
In routes/index.js
, set up the routes for your Markdown editor:
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.render('index', { markdownContent: '' });
});
module.exports = router;
Step 5: Create Views
In views/index.ejs
, create the template for the Markdown editor:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/styles/main.css">
<title>Markdown Editor</title>
</head>
<body>
<div class="editor-container">
<textarea id="markdown-input" placeholder="Type your markdown here..."></textarea>
<div id="markdown-preview"></div>
</div>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script>
const inputElement = document.getElementById('markdown-input');
const previewElement = document.getElementById('markdown-preview');
inputElement.addEventListener('input', () => {
const markdownContent = inputElement.value;
const htmlContent = marked(markdownContent);
previewElement.innerHTML = htmlContent;
});
</script>
</body>
</html>
Step 6: Create CSS Styles
In public/styles/main.css
, add your styles:
body {
font-family: 'Arial', sans-serif;
margin: 20px;
}
.editor-container {
display: flex;
justify-content: space-between;
}
textarea {
width: 45%;
height: 300px;
padding: 10px;
}
#markdown-preview {
width: 45%;
height: 300px;
padding: 10px;
border: 1px solid #ddd;
overflow-y: auto;
}
Step 7: Run Your Application
Start the Express server:
node app.js
Visit http://localhost:3000 in your browser, and you should see your simple Markdown editor. As you type in the textarea, the preview will update in real-time.
Feel free to enhance the application by adding more features like saving and loading markdown content, integrating with a database, or allowing users to download their markdown content.