10 Node.js Boilerplate Code Snippets Every Developer Needs

get_pieces

Pieces 🌟

Posted on February 6, 2024

10 Node.js Boilerplate Code Snippets Every Developer Needs

Node.js is a game-changer in web development. It lets developers use JavaScript seamlessly from the browser to the server. Its event-driven setup is like a multitasking superhero, making it perfect for applications with simultaneous tasks, such as chat apps and online games.

It excels as a web server superhero, effortlessly handling multiple users and creating snappy APIs for real-time applications like chats and gaming. It's not just for the web; Node.js fits into microservices architectures and even tackles desktop applications with frameworks like Flutter or Electron.

Node.js is your trusty sidekick, making web development more enjoyable and efficient. In this article, we are going to dive into some super useful Node.js boilerplate snippets that will become an indispensable part of your workflow.

As you add them to your workflow, you’ll need to go back to these snippets over and over again. We will help you overcome this tedious task!

Rather than searching your notes endlessly, you can use Pieces for Developers to organize these Node.js code snippets along with the useful links, tags, helpful descriptions, anchors, and titles for each snippet, making it a <1-second task to retrieve one whenever you need it. Ready to get started? Install the Pieces Desktop App for free.

Let's dive in!

1. CORS in Node.js Express Boilerplate

Using Node.js CORS is a mechanism that allows a web server to specify which domains are allowed to access its resources. When a client makes a request to a server, the server includes a special header called Access-Control-Allow-Origin in its response. This header specifies which domain is allowed to access the resources. If the requesting domain is not in the allowed list, the browser will block the request.

Here is a boilerplate Node.js snippet to enable all CORS requests:

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})
Enter fullscreen mode Exit fullscreen mode

Save this code

2. Enable CORS for a Single Route

If you need a certain route to be accessible and not other routes, you can configure CORS as a middleware instead of configuring it to the whole app. This will allow a certain route to be accessible by any domain. In this case, only the / route will be accessible for every domain. Here's a Node.js express boilerplate for enabling CORS:

var express = require('express')
var cors = require('cors')
var app = express()

app.get('/products/:id', cors(), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for a Single Route'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})
Enter fullscreen mode Exit fullscreen mode

Save this code

3. Basic Morgan Usage

Adding Morgan to middlewares in Express is enough to get you started. The below setup will start logging requests in the console.

Here's a simple Node.js boilerplate for basic Morgan usage:

const express = require('express');
const morgan = require('morgan'); // import morgan
const app = express();

// setup morgan
app.use(morgan("dev"));

app.listen(3000, () => {
    console.debug('App listening on :3000');
})
Enter fullscreen mode Exit fullscreen mode

Save this code

4. Customize Log Formats by Creating Our Own Tokens

Tokens in Morgan are functions identified following the : symbol. Morgan allows you to create your own tokens with the .token() method.

The .token() method accepts a type or the name of the token as the first argument, following a callback function. Morgan will run the callback function each time a log occurs using the token. As a middleware, Morgan applies the req and res objects as arguments.

Here's a boilerplate Node.js snippet for creating custom logs:

import express from 'express';
import morgan from 'morgan';
const app=express();
morgan.token('host', function(req, res) {
return req.hostname;
});
// we are using the host parameter
app.use(morgan(':method :host :status :res[content-length] - :response-time ms'))
app.get("/", (req, res) => {
res.send("<h1>Hello world!</h1>");
});
app.listen(3000,()=>{
console.log('Listening on port 3000...')
})
Enter fullscreen mode Exit fullscreen mode

Save this code

5. Design Tokens with Custom Arguments

To denote custom arguments, you can use square brackets to define arguments passed to a token. This will allow your tokens to accept additional arguments. In your index.js file, apply a custom argument to the Morgan format string in the :param token.

Here's a simple boilerplate Node.js snippet:

app.use(morgan(':method :host :status :param[id]:res[content-length] - :response-time ms')); 
morgan.token('param', function(req, res, param) { 
return req.params[param]; });
Enter fullscreen mode Exit fullscreen mode

The custom argument ID on the :param token in the Morgan invocation will include the ID in the parameter following the .token() method.

Save this code

6. Create a Simple HTTP Server in Node.js to Serve a String

A simple HTTP server listens at port 3000 and is used to serve a string. Here's a simple boilerplate Node.js code snippet:

// Load the 'http' module
const http = require('http');

// Create an HTTP server that responds with a string
const server = http.createServer((req, res) => {
  // Set the content type to plain text
  res.setHeader('Content-Type', 'text/plain');

  // Send the string as the response
  res.end('Hello, this is a simple HTTP server in Node.js!');
});

// Specify the port number on which the server should listen
const port = 3000;

// Start the server and listen on the specified port
server.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
});
Enter fullscreen mode Exit fullscreen mode

Save this code

7. Create a Simple HTTP Server in Node.js to serve HTML

This code snippet creates a simple HTTP server that listens at port 3000 and is used to serve HTML:

//serve-html.js
var http = require('http');
var fs = require('fs');


http.createServer(function (req, res) {
    console.log("Port Number : 3000");
    // change the MIME type from 'text/plain' to 'text/html'
    res.writeHead(200, {'Content-Type': 'text/html'});
    //reading the content file
    fs.readFile('index.html', (err, data) => {
        //checking for errors
        if (err) 
            throw err;
        console.log("Operation Success");
        //sending the response
        res.end(data);
    });
}).listen(3000);
Enter fullscreen mode Exit fullscreen mode

Save this code

8. Create a Simple HTTP Server in Node.js to Serve a PDF

Here is the boilerplate Node.js code to create a simple HTTP server that listens at port 3000 and is used to serve a PDF:

//serve-pdf.js
var http = require('http');
var fs = require('fs');
console.log('Server will listen at :  127.0.0.1:3000 ');
http.createServer( (req, res)=> {
    console.log("Port Number : 3000");
    // Change the MIME type to application/pdf
    res.writeHead(200, {"Content-Type": "application/pdf"});

    fs.readFile('index.pdf', (error,data) => {
        if(error){
            res.json({'status':'error',msg:err});
        }else{          
            res.write(data);
            res.end();       
        }
    });
}).listen(3000);
Enter fullscreen mode Exit fullscreen mode

Save this code

9. Create a Simple HTTP Server in Node.js to Serve Audio

Here is the boilerplate Node.js code to create a simple HTTP server that listens at port 3000 and is used to serve audio:

//serve-audio.js
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
    console.log("Port Number : 3000");
    // change MIME type to 'audio/mp3'
    res.writeHead(200, {'Content-Type': 'audio/mp3'});
    fs.exists('audio.mp3',function(exists){
        if(exists)
        {
            var rstream = fs.createReadStream('audio.mp3');
            rstream.pipe(res);
        }
        else
        {
            res.end("Its a 404");
        }
    });
}).listen(3000);
Enter fullscreen mode Exit fullscreen mode

Save this code

10. Create a Simple HTTP Server in Node.js to Serve Video

Here is the boilerplate Node.js to create a simple HTTP server that listens at port 3000 and is used to serve video:

//serve-video.js
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
    console.log("Port Number : 3000");
    // change the MIME type to 'video/mp4'
    res.writeHead(200, {'Content-Type': 'video/mp4'});
    fs.exists('video.mp4',function(exists){
        if(exists)
        {
            var rstream = fs.createReadStream('video.mp4');
            rstream.pipe(res);
        }
        else
        {
            res.send("Its a 404");
            res.end();
        }
    });
}).listen(3000);
Enter fullscreen mode Exit fullscreen mode

Save this code

Conclusion

That wraps up our handpicked collection of the best Node.js boilerplate code snippets —a valuable resource for both seasoned Node.js developers and those just starting out.

For a seamless coding experience and accelerated learning, the Pieces Web Extension offers a nifty feature. You can effortlessly copy and save any of these Node.js boilerplate codes from our list, making them instantly accessible whenever you need them.

What's even more fascinating is that as you save a snippet in Pieces, you'll gain insight into those boilerplate Node.js snippets, including tags, context, and relevant links. Sounds intriguing, right? Give it a shot! Try saving one of the code snippets above with just a single click, enriched with tags and all the context you need, and install the Pieces Desktop App.

We hope this article has helped you get comfortable with some handy Node.js boilerplate snippets and when to use them. If you're keen on discovering more useful code snippets, make sure to check out the Pieces Node.js code snippets collection.

💖 💪 🙅 🚩
get_pieces
Pieces 🌟

Posted on February 6, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related