An extensive guide to build your NPM package and publish it.
Tags: javascript, npm, node, tutorial
Published: 2022-06-23 21:31:15




Hey folks, I hope you all are doing great. I've been building APIs and backends using `NodeJS` and `ExpressJS` for a while now and the one thing that I find most tedious is setting up the project.

It includes: 

- Making directories like:
	- Middlewares
	- Routes
	- Database
	- Models
- Setting up the boilerplate code in the index.js or the server.js file. 
- Making .env  files and storing the secrets. 
- Installing usually used packages like:
	- CORS
	- ExpressJS
	- JWT
	- BcryptJS
	- DOTENV

We are going to make this whole process happen with just one command. 

## What are we going to build? 
We are going to build a backend builder which lets us create the necessary folders, files and initialise the server with a basic get route. It will also install all the packages required for the server to work. So let's get started. 

### Step-1 : Making NPM Account
- Make an account on NPM and login to the account. 


### Step-2 :  Setting up the project
- Make an empty directory/folder. 
- Create a js file named as `bin.js` in the folder.
- Run npm init in that empty folder and set the entry point as `bin.js`.
- This will create a package.json file.
- Modify that file according to the below image. 

![package.json image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j2580bfyc01uuifodmbu.png)

### Step-3 : Coding
- Inside the `bin.js` file import these three packages. 

```js
#!/usr/bin/env node

const process = require("process");
const fs = require("fs");
const child_process = require("child_process");
```

- We do not have to download these packages as they are inbuilt in NodeJS. 
- We use shebang code `(#!/usr/bin/env node)` to tell the kernel which interpreter should be used to run the file. You can simply ignore it. 
- When a user uses the package, they should get an intimation that some process is happening. So to do that add these two `console.log()` into the file. 

```js
// for user intimation
console.log("Building folders and initialising your server...⛳️");

console.log(
  "This might take few seconds...⏳"
);

```

- Now we have to create three folders:
   - db 
   - routes
   - models

- In order to do so we will use `fs.mkdirSync()`. mkdir means make directory and sync means it will make directory synchronously. 
- Add the below code to create folders. 

```js
// make folders
fs.mkdirSync(`${process.cwd()}/db`);
fs.mkdirSync(`${process.cwd()}/model`);
fs.mkdirSync(`${process.cwd()}/routes`);
```

- You might see that I have used `process.cwd()`. This means the folders would be created in the current working directory (cwd) in which our package or `npx executable` command would be used. 

- Now we have to install some packages so that our server could run. 
- We will install: 
  - express
  - cors
  - jwt
  - dotenv
  - bcryptjs
  - nodemon (dev dependency)

- If we want to run commands using a package we would have to use `child_process.execSync()`. 

- `child_process` enables us to spawn subprocesses inside the main / parent process. 

- `execSync` lets us execute shell/terminal commands using nodejs. 
- Use the code given below for reference. 

```js

//  install packages
child_process.execSync("npm init -y", { stdio: [] });
child_process.execSync("npm install express", { stdio: [] });
child_process.execSync("npm install cors", { stdio: [] });
child_process.execSync("npm i jsonwebtoken", { stdio: [] });
child_process.execSync("npm i dotenv", { stdio: [] });
child_process.execSync("npm i bcryptjs", { stdio: [] });
child_process.execSync("npm i -D nodemon", { stdio: [] });


```

- Now we have to create a `.env` file to store secrets in it. 
- To make a file use a method `fs.appendFileSync()`. It adds the given data to the file and by any chance if the file is not present then it creates the file and writes the data in it. 

```js
fs.appendFileSync(`${process.cwd()}/.env`, `PORT=8080`);
```


- Now we have to make the `server.js` file and write some boilerplate code in it. 
- We will use the same function as above. 

```js
fs.appendFileSync(
  `${process.cwd()}/server.js`,
  `
const express = require('express');
const app = express();
require('dotenv').config();
const cors = require('cors');

// middlewares
app.use(cors());
app.use(express.json());

// defining port
const PORT = process.env.PORT || 3001;

// setting up an empty GET Route
app.get('/', (req, res)=>{res.json({message: "You've come to the right place... it's a GET request!!"})});

// Starting Server on PORT
app.listen(PORT, () => console.log('Server started on PORT Number: ' + PORT))
`
);

```

- The first argument in `fs.appendFileSync()` is the path to the file and the second argument is the data to be written in the file. 

- If we are going to push the data to a repository we will need a `.gitignore` file. So we will create that as well. 

```js
fs.appendFileSync(`${process.cwd()}/.gitignore`, 
`
node_modules 
.env
`);
```

- Now we will add a final intimation saying that everything is completed and you may use the project now. 

```js
console.log(
  "Folders are created and server.js is initialized with boilerplate code...\n RUN: nodemon server.js \nHappy Coding ✨"
);
```


### Step-4 : Publishing your NPM package
- Navigate to the root directory of your project and run the following command. 
```shell
npm publish --access=public
```

> To use the package, run `npx @your_username/projectname@latest`

Drum Roll 🥁!!

You have made your NPM package which handles the boring and tedious task of setting up a backend and you have published it as well. Thank you for reading the blog ✨. 


View full Code:

{% replit @shreyazz/backendbuilder %}