Kickstart Node.js for Front-End Developers: From Basics to HTTP APIs
This tutorial walks front‑end engineers through the fundamentals of Node.js, covering its runtime concept, installation, basic file operations, built‑in APIs, creating HTTP servers, using the Koa framework, simple database interactions, and calling third‑party services, all with clear code examples.
Getting Started
Node.js was released in 2009 and by August 2025 has reached version 24, becoming one of the most popular development runtimes. It powers many cloud platforms, Serverless services, and is a convenient entry point for front‑end developers interested in AI development.
JS Runtime
A piece of JavaScript code is essentially a string. In browsers, the <script> tag embeds this string and the built‑in JS engine executes it. The execution environment of a language is called a runtime . Node.js is the second JavaScript runtime after browsers, allowing JS to run on any operating system without a browser.
Other runtimes such as Deno and Bun exist but are less widespread.
Installing Node.js and Writing a Demo
After installing Node.js, run node --version and npm --version to verify the installation. Enter the REPL with node, write any JS code, and exit with Ctrl+C.
Create a test.js file:
// src/test.js
function fn() {
console.log('this is a test file');
}
fn();Execute it with node test.js to see the expected output.
Cannot Use Browser APIs
Node.js can execute JavaScript but lacks browser APIs such as alert, document, or window. Attempting to call them results in "alert is not defined" errors.
Node.js Built‑in APIs
Node.js provides OS‑related APIs. Example os.js:
// src/os.js
const os = require('os');
function getSystemInfo() {
return {
platform: os.platform(),
type: os.type(),
architecture: os.arch(),
cpuCount: os.cpus().length,
cpuModel: os.cpus()[0].model,
totalMemoryGB: Math.round(os.totalmem() / 1024 / 1024 / 1024),
hostname: os.hostname()
};
}
const systemInfo = getSystemInfo();
console.log(systemInfo);Run it with node os.js to print system information.
File API
Node.js can manipulate the file system. Example file.js creates, writes, and reads data.txt:
const fs = require('fs');
const path = require('path');
const fileDir = path.join(__dirname, '../file');
const filePath = path.join(fileDir, 'data.txt');
function createAndWriteFile() {
if (!fs.existsSync(fileDir)) {
fs.mkdirSync(fileDir, { recursive: true });
console.log('Created directory:', fileDir);
}
const content = 'Hello from Node.js file API';
fs.writeFileSync(filePath, content, 'utf8');
console.log('File created:', filePath);
console.log('Content written:', content);
}
createAndWriteFile();
function readFile() {
try {
const data = fs.readFileSync(filePath, 'utf8');
console.log('Read file content:', data);
return data;
} catch (error) {
console.error('Failed to read file:', error.message);
return null;
}
}
readFile();HTTP Service
Node.js enables full‑stack development. Create http.js to start a simple GET server:
const http = require('http');
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'application/json');
const response = {
message: 'Hello World!',
time: new Date().toLocaleString(),
status: 'success'
};
res.end(JSON.stringify(response, null, 2));
});
server.listen(3000, () => {
console.log('HTTP server started on port: 3000');
console.log('Visit: http://localhost:3000');
});Run with node http.js and visit http://localhost:3000 to see the JSON response.
For a POST endpoint, create http‑post.js:
const http = require('http');
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'application/json');
if (req.method === 'POST' && req.url === '/api/user') {
let body = '';
req.on('data', chunk => { body += chunk.toString(); });
req.on('end', () => {
try {
const userData = JSON.parse(body);
console.log('Received user data:', userData);
const response = { status: 'success' };
res.statusCode = 200;
res.end(JSON.stringify(response));
} catch (error) {
const response = { status: 'error', message: 'Invalid JSON' };
res.statusCode = 400;
res.end(JSON.stringify(response));
}
});
} else {
const response = { message: 'Send POST to /api/user' };
res.end(JSON.stringify(response));
}
});
server.listen(3000, () => {
console.log('HTTP server started on port: 3000');
console.log('POST endpoint: http://localhost:3000/api/user');
});Test with curl or Postman.
Koa Framework
Initialize a project with npm init -y, install Koa and nodemon, then create src/index.js:
// src/index.js
const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);Add a dev script "dev": "nodemon src/index.js" and run npm run dev to start the server.
For JSON responses, assign an object to ctx.body. To handle POST/PUT, install koa-body and use ctx.method to branch logic.
const Koa = require('koa');
const { koaBody } = require('koa-body');
const app = new Koa();
app.use(koaBody());
app.use(async ctx => {
if (ctx.method === 'POST') {
const { user, email } = ctx.request.body || {};
console.log('user and email', user, email);
ctx.body = { status: 'success', user, email };
}
});
app.listen(3000);Install @koa/router for routing:
const Koa = require('koa');
const koaBody = require('koa-body');
const Router = require('@koa/router');
const app = new Koa();
const router = new Router();
app.use(koaBody());
router.post('/api/user', ctx => {
const { user, email } = ctx.request.body || {};
console.log('user and email', user, email);
ctx.body = { status: 'success', user, email };
});
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000);Database Operations
Modern web apps often use an ORM such as Prisma instead of raw SQL. Example creating a user and fetching all users:
async function main() {
await prisma.user.create({
data: { name: 'Alice', email: '[email protected]' }
});
const allUsers = await prisma.user.findMany();
console.log(allUsers);
}A more complex example creates related posts and profile records in a single transaction and queries them together:
async function main() {
await prisma.user.create({
data: {
name: 'Alice',
email: '[email protected]',
posts: { create: { title: 'Hello World' } },
profile: { create: { bio: 'I like turtles' } }
}
});
const allUsers = await prisma.user.findMany({
include: { posts: true, profile: true }
});
console.dir(allUsers, { depth: null });
}Calling Third‑Party Services
Third‑party APIs can be called directly with fetch or via SDKs. Example using fetch to call DeepSeek:
await fetch('https://api.deepseek.com/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer <DeepSeek API Key>'
},
body: JSON.stringify({
model: 'deepseek-chat',
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'Hello!' }
],
stream: false
})
});Or install the OpenAI SDK (which also works with DeepSeek) and call the API:
import OpenAI from "openai";
const openai = new OpenAI({
baseURL: 'https://api.deepseek.com',
apiKey: '<DeepSeek API Key>'
});
async function main() {
const completion = await openai.chat.completions.create({
model: 'deepseek-chat',
messages: [{ role: 'system', content: 'You are a helpful assistant.' }]
});
console.log(completion.choices[0].message.content);
}
main();Integrate these calls into your Node.js server to build custom AI services.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
