DEV Community

Cover image for Let's create a React File Manager Chapter XV: Lets make server with typescript and express
Hasan Zohdy
Hasan Zohdy

Posted on

 

Let's create a React File Manager Chapter XV: Lets make server with typescript and express

Today we're going to stop react for a little and create a quick simple Express server to serve our files.

The purpose of this is to serve our file manager only so we won't go deeper.

Express for those who are not familiar with it, is a simple Node.js framework that helps you create a server easily.

Preparing our server

Let's create a new directory beside our react directory and name it server and rename our React js project to be client so we can easily distinguish between them.

Installation

We're not going deeply into express installation, you can read the official documentation for that.

Let's add the following packages

yarn add @faker-js/faker @mongez/fs express

Faker to generate our fake data and @mongez/fs to help us with our file system.

Now let's add dev dependencies.

yarn add -D typescript ts-node tslib @types/express @types/node

Typescript for of course to allow ts files, ts-node to run our ts files, tslib to help us with our typescript files and @types/express and @types/node to help us with our typescript files.

Initializing Typescript

Simply run the following command.

yarn tsc --init

Generating Directories and Files

We need to create two directories, src that will manage our server and generator and data to store files and directories inside it.

Let's create src/generator.ts file and add the following code:

import fs from "@mongez/fs";
import { faker } from "@faker-js/faker";

const dataDirectory = process.cwd() + "/data";
Enter fullscreen mode Exit fullscreen mode

process.cwd() is the current working directory, which we can call it our root directory, so we're going to create our data directory inside it.

Here we simply imported our @mongez/fs package and faker to generate our fake data.

dataDirectory is the directory where we're going to store our files and directories.

import { faker } from "@faker-js/faker";
import fs from "@mongez/fs";

const dataDirectory = process.cwd() + "/data";

function start() {
  make(3, 3, dataDirectory);
}

start();
Enter fullscreen mode Exit fullscreen mode

We created a function called start and called it at the end of the file.

Then we called another function called make and passed it 3 arguments, the first one is the number of directories we want to create, the second one is the number of files we want to create and the third one is the directory path that we need to create directories and files inside it.

import { faker } from "@faker-js/faker";
import fs from "@mongez/fs";

const dataDirectory = process.cwd() + "/data";

function start() {
  make(3, 3, dataDirectory);
}

start();

function makeFiles(maxFilesPerDirectory: number, path: string) {
  const filesList: string[] = [];

  while (filesList.length < maxFilesPerDirectory) {
    const file = faker.system.fileName();
    const filePath = path + "/" + file;
    if (!filesList.includes(filePath) && !fs.isFile(filePath)) {
      filesList.push(filePath);
      fs.put(filePath, faker.lorem.paragraphs());
    }
  }
}

function make(
  maxDirectories: number,
  maxFilesPerDirectory: number,
  path: string
) {
  const directoriesList: string[] = [];

  while (directoriesList.length < maxDirectories) {
    const directory = faker.system.directoryPath().split("/")[1];
    const directoryPath = path + "/" + directory;
    if (
      !directoriesList.includes(directoryPath) &&
      !fs.isDirectory(directoryPath)
    ) {
      directoriesList.push(directoryPath);
      fs.makeDirectory(directoryPath, 777);
      makeFiles(maxFilesPerDirectory, directoryPath);
      // 👇🏻  to make recursive directories and files, you'll need to stop the script after some time
      // 👇🏻  and run it again
      // 👉🏻  make(maxDirectories, maxFilesPerDirectory, directoryPath);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Here we created two functions, the first one is makeFiles and the second one is make.

makeFiles is responsible for creating files inside a directory, it takes two arguments, the first one is the number of files we want to create and the second one is the directory path that we need to create files inside it.

In make function we'll store the directories that we created in an array called directoriesList and we'll loop through it until we reach the number of directories we want to create.

Only directories that are really does not exist will count and stored in the directoriesList array.

Then we'll call makeFiles function to create files inside the directory.

After calling makeFiles i've added make(maxDirectories, maxFilesPerDirectory, directoryPath); and commented it.

This command will make recursive directories and files, but you'll need to stop the script after some time and run it again.

Running The Generator

Open package.json file and add scripts object and add the following code:

  "scripts": {
    "generate": "npx ts-node ./src/generator.ts",
    "start": "npx ts-node ./src/index.ts"
  },
Enter fullscreen mode Exit fullscreen mode

We added generate script to run our generator and start script to run our server.

But we'll not use start script for now, we'll use it later.

Now let's run our generator.

yarn generate

After running and stopping the command multiple times, we'll have a directory called data that contains directories and files.

Data directory

Initializing the server

Now let's make a simple server so we can send requests over it, create src/index.ts file and let's import express.

// src/index.ts
// imported express server
import express, { Express, Request, Response } from "express";

// port to run the server
const port = 3001;

// create express app
const app: Express = express();

// define a route handler for the default home page
app.get("/", (req: Request, res: Response) => {
  res.send("Express + TypeScript Server");
});

// start the Express server
app.listen(port, () => {
  console.log(`⚡️[server]: Server is running at http://localhost:${port}`);
});
// imported express server
import express, { Express, Request, Response } from "express";

// port to run the server
const port = 8001;

// create express app
const app: Express = express();

// define a route handler for the default home page
app.get("/", (req: Request, res: Response) => {
  res.send("Welcome to File Manager");
});

// start the Express server
app.listen(port, () => {
  console.log(`⚡️[server]: Server is running at http://localhost:8001`);
});
Enter fullscreen mode Exit fullscreen mode

The code is very simple, we created an express server and defined a route handler for the default home page which will display Welcome to File Manager.

Now let's run our server.

yarn start

You should see in the terminal ⚡️[server]: Server is running at http://localhost:${port}

Now open the browser and navigate to http://localhost:8001 and you should see Welcome to File Manager in the browser.

In the next chapter

We'll create the following routes:

  • GET /file-manager to get files and directories.
  • POST /file-manager to create a new directory.
  • DELETE /file-manager to delete a directory.
  • PUT /file-manager to rename a directory.

Article Repository

You can see chapter files in Github Repository

Don't forget the main branch has the latest updated code.

Tell me where you are now

If you're following up with me this series, tell me where are you now and what you're struggling with, i'll try to help you as much as i can.

Salam.

Top comments (1)

Collapse
 
shenzhongkang profile image
Zhongkang Shen

How to fix permission error when exec yarn generate?

Error: EACCES: permission denied, open /Users/code/file-manager-react/server/data/sbin/tuna.x_b
Enter fullscreen mode Exit fullscreen mode

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post