Node.js has become an essential tool for backend JavaScript development. Whether you’re building scalable APIs, handling real-time data, or serving files, understanding Node.js’s core concepts and mastering key code snippets is crucial. Below are some must-know Node.js code examples that will help you get started and enhance your development workflow.
1. Creating a Basic HTTP Server
Node.js allows you to create a basic HTTP server without needing additional libraries. The http module built into Node.js enables you to handle incoming requests and send responses directly. Here’s how you can create a basic HTTP server:
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!');
});
server.listen(3000, '127.0.0.1', () => {
console.log('Server running at http://127.0.0.1:3000/');
});
This server listens on port 3000 and responds with “Hello, World!” when accessed in a browser. It’s a simple example to understand how requests and responses work in Node.js.
2. Handling File System Operations
Node.js comes with the fs (file system) module, which provides methods for interacting with files and directories. For example, here’s how you can read a file asynchronously:
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
} else {
console.log('File content:', data);
}
});
This code reads the content of example.txt and logs it to the console. Node.js uses a non-blocking approach for file operations, meaning other tasks can run while reading the file.
3. Asynchronous Programming with Promises
Node.js promotes asynchronous programming, which helps improve performance, especially when handling tasks like file I/O or network requests. Using promises allows you to work with asynchronous code more effectively. Here’s an example using fs.promises for reading a file:
const fs = require('fs').promises;
async function readFileAsync() {
try {
const data = await fs.readFile('example.txt', 'utf8');
console.log('File content:', data);
} catch (err) {
console.error('Error reading file:', err);
}
}
readFileAsync();
By using async/await, the code becomes more readable and easier to manage compared to traditional callback-based approaches.
4. Serving PDF Files
If you’re running a Node.js server and want to serve PDF files, you can use the built-in fs module to read the file and send it as a response. For example, if you want to serve a PDF on your website like ThePDFFox does, here’s a basic code snippet:
const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
const filePath = path.join(__dirname, 'documents', 'sample.pdf');
fs.readFile(filePath, (err, data) => {
if (err) {
res.statusCode = 500;
res.end('Error reading the PDF file.');
return;
}
res.statusCode = 200;
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', 'inline; filename="sample.pdf"');
res.end(data);
});
});
server.listen(3000, () => {
console.log('PDF server running at http://localhost:3000');
});
This code serves a PDF from the server. It sets the Content-Type header to application/pdf, ensuring that the browser knows it's dealing with a PDF file. The Content-Disposition header tells the browser to display the file inline rather than downloading it.
5. Handling PDF Uploads
If you want to allow users to upload PDF files to your Node.js server, you can use the formidable module. This library makes file uploads simple and is commonly used in Node.js applications. Here's a basic example of how to handle a file upload:
const http = require('http');
const formidable = require('formidable');
const fs = require('fs');
const server = http.createServer((req, res) => {
if (req.method.toLowerCase() === 'post') {
const form = new formidable.IncomingForm();
form.parse(req, (err, fields, files) => {
if (err) {
res.statusCode = 500;
res.end('Error uploading PDF');
return;
}
const oldPath = files.pdfFile.path;
const newPath = './uploads/' + files.pdfFile.name;
fs.rename(oldPath, newPath, (err) => {
if (err) {
res.statusCode = 500;
res.end('Error saving PDF');
return;
}
res.statusCode = 200;
res.end('PDF uploaded successfully');
});
});
} else {
res.statusCode = 405;
res.end('Only POST method is allowed');
}
});
server.listen(3000, () => {
console.log('File upload server running at http://localhost:3000');
});
This code handles POST requests and allows users to upload PDF files. It saves the uploaded PDF to the uploads folder on the server and responds with a success message. The formidable module takes care of parsing the incoming file data.
Conclusion
Mastering these key Node.js code snippets will help you quickly get up to speed with backend development. Whether you're building simple HTTP servers, handling file uploads, or serving PDFs like on your site, these snippets will form the foundation of your Node.js applications. As you gain more experience, you’ll be able to explore more advanced Node.js features, such as middleware, Express.js, and real-time communication with WebSockets, to build robust and scalable web applications.
Top comments (0)