Author: Grant G

  • How to Add NPM Packages in Bun JS

    Bun JS has an insanely fast package installer which is one great reason to upgrade to it over Node!

    To install a package in bun simply use:

    bun add [PACKAGE_NAME]

    For example, install figlet (ASCII art) and its typings:

    bun add figlet
    bun add -d @types/figlet 

  • Bun js Hot Reload – Full Guide

    Bun incudes 2 very handy flags that will watch your project for file changes. I also cover this in my bun Elysia course.

    1. Reload with the –watch flag

    This is used in the command to run your server, eg:

    bun --watch index.ts

    If a files contents change within your project folder then bun will cold reload your project – equivalent to restarting the server. All states and connections will be destroyed.

    2. Reload with the –hot flag

    bun --hot index.ts

    Again, if files change then bun will reload your project but only the code directly affected. This keeps state and connections open. Obviously if the changed code affects state or connection then you may have very strange debug issues!

    Personally I like to just use –watch. I have very very few instances where it would save my time to keep state or connections. However, I could see the use for it on a production server so there was a minimum of user disruption.

    If you want to know more then see my full hot reload guide here.

    Alternatively you can also check out my course on bun and Elysia Framework, which has everything you need to get you started.

  • How to Create a Server in native Bun JS

    Note that these instructions are for installing on Mac. Linux or WSL on Windows. Native Windows is experimental at this point (2023) so best to avoid it for now.

    Open up a folder in VS Code where your project will live.

    Open up a terminal within VS Code and enter:

    npm install -g bun

    This will install bun for global use on your system.

    Spin up a new bun server:

    bun init

    This will create an index.ts file, package.json and a typescript config file with the bun standard settings.

    Open up the index.ts file and paste in:

    const server = Bun.serve({
      port: 3000,
      fetch(request) {
        return new Response("Welcome to Bun!");
      },
    });
    
    console.log(`Listening on localhost: ${server.port}`);

    Now, in your terminal run the following command:

    bun index.ts

    Your server should now be running – as the console log message will tell you.

    Open up a browser and go to: localhost:3000. You should see a ‘Welcome to Bun!’ message.

    Finally, if you change some code in the index.ts file then you will need to quit the bun run time and restart it. However there is a handy watcher feature in bun. Instead of ‘bun index.ts’ now you can add in –watch:

    bun --watch index.ts

    This will reload the server (cold start) every time the file receives a change. Alternatively you can use the –hot flag to keep the server running and simply slot in the code you’ve changed.

    bun --hot index.ts

    The latter –hot version keeps the state of your server and any current connections so could come in quite handy!

    Any question or clarifications? Please leave them in the comments!

  • Create a Basic Express JS Server

    This server will print out a “hello world” to a local webpage on your PC. The steps are simple:

    Step 1: Install Node JS

    Go here https://nodejs.org/en/download/ and download the installer for your system (Max / Windows / Linux). Once installed verify by opening a cmd or terminal and typing

    “node -v && npm -v”

    This will verify that node and node package manager (npm) are installed. Any errors should be searched for on Stack Overflow.

    Step 2: Setup the project

    Many tutorials miss out this step. If you’re new here then what you need to know is:

    • Node / React / Angular / many other projects start from a single file called package.json
    • package.json is simply a configuration file that tells your system
      • Some details about the project, such as name
      • What packages or “dependencies” your project needs, generally these come from NPM
      • Many other possibilities (but that’s not needed right now)
    Step 3: Create a Basic Node Project
    • Create a folder on your computer and name it (for example) basic-express-app.
    • Open that folder in Visual Studio Code, or whatever code editor you’re using.
    Step 4: Use NPM to Start the Project
    • Open a terminal or command line. If using VS Code you can do this is the “terminal” menu.
    • Type “npm init” and accept the basic answers to the questions.
    • Npm will create a basic package.json file and our project is ready to install
    • In the terminal type “npm i” which will install the dependencies (there are none right now but the system will tell you that everything is up to date anyway)
    Step 5: Create an index.js file
    • You have a package.json and in that file it should have a “main” entry. This tells the app where to start when it is run. It should say index.js right now.
    • Create the “index.js” file in the root of your folder, leave it empty for now.
    Step 6: Install Express

    Express is a framework that sits on top of Node JS and makes creating a server MUCH easier! There are alternative framworks such as Hapi JS etc but Express is very popular and much loved.

    (Developer lesson: stick with much loved projects because they’re most likely to still be around in a decade, when you come back to your ancient code!)

    Grant @ iamdev
    • In the terminal type: “npm i express” and hit enter
    • This will fetch Express from npm and install it in “node_modules” folder

    Congratulations, all we have to do now is write our first server code!

    Step 7: Paste into index.js

    Take the following code and paste it into index.js:

    const express = require(‘express’)
    const app = express();
    const port = 3001;

    app.get(‘/’, (req, res) => {
    res.send(‘Hello World, I\’m a server!’);
    });

    app.listen(port, () => {
    console.log(`App listening at http://localhost:${port}`);
    });

    So what does each line do?

    const express = require(‘express’)
    const app = express();
    const port = 3001;

    Here we tell our app to pull in the Express dependency (1st line) and then initialise the express server (2nd line). Finally we tell the app which port to use out of the thousands available on our PC. This is important as we may have multiple servers on one system (although I wouldn’t advise it) so each one must have a unique port it can use.

    Behind the scenes express JS is doing a lot of heavy lifting and abstracting away all the painful tasks!

    app.get(‘/’, (req, res) => {
    res.send(‘Hello World, I\’m a server!’);
    });

    app.listen(port, () => {
    console.log(`App listening at http://localhost:${port}`);
    });

    The last 3 lines in this section tell the express app to listen to the port we specified. Whenever a packet reaches that port the app captures it and then later on will route it on to its destination.

    The first 3 lines define a single destination for the app. The destination is ‘/’ in this case, which means the root destination. For example: facebook.com is also a root destination, but facebook.com/messenger is not.

    Within the block we see req, res which are objects that hold information about the request and the response. Request is what the person using your site sent (eg, address, header, body, IP etc). Response contains data and methods we can use to return an answer to the person who sent the request.

    Finally you can see that the “res.send” line returns a message to the user. In this case it’s a simple string with a message. Most of the time you’ll have more structure than a string – we usually send data formatted in JSON (javascript object notation) – but that’s for another day.

    Step 8: Run the Server
    • Go to your terminal and type “node index.js”
    • Your app will now run, and stay running. You should get a message like:
      App listening at http://localhost:3001

    Congratulations you have built a server! To see it running:

    • Open a browser and go to localhost:3001

    You should see a message welcoming you to the dark world of back end server creation 🙂

    Note that this will only work on your current PC. It doesn’t work on the web (yet).