How to serve JavaScript files in Node.js
To serve JavaScript files in Node.js, you'll typically use the http
or express
module. Below are two common methods:
Method 1: Using the http
Module
-
Create a Server: Start by creating an HTTP server using the
http
module. -
Serve the JavaScript File: Read the JavaScript file using the
fs
(file system) module and serve it in response to requests.
Here's an example:
const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
if (req.url === '/script.js') {
// Set the content type to JavaScript
res.writeHead(200, { 'Content-Type': 'application/javascript' });
// Read the JavaScript file and serve it
fs.readFile(path.join(__dirname, 'script.js'), 'utf8', (err, data) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
} else {
res.end(data);
}
});
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
Method 2: Using the express
Module
-
Install Express: If you don't already have it, install Express by running
npm install express
. -
Create an Express Application: Use Express's static middleware to serve static files like JavaScript.
Here's an example:
const express = require('express');
const path = require('path');
const app = express();
// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
In this example, if you have a script.js
file in a public
directory, you can access it at http://localhost:3000/script.js
.
Explanation:
-
http Module:
- You manually handle requests and serve files.
- Good for learning and small projects but can become cumbersome for larger applications.
-
express Module:
- Express makes it easier to serve static files with minimal setup.
- It's widely used in production applications for its simplicity and scalability.
These methods allow you to serve JavaScript files and other static assets in a Node.js environment.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.