Skip to main content

Server and client combined

Drayman allows using server-side and client-side code together. This allows you to easily combine server-side libraries, file-system queries, database connections, managing user-sensitive data and creating UI inside single script.

On this page you will find out how to easily build user list manager using Node.js library fs-extra.

Building full stack component#

Let's build UI for adding user data to JSON file. First, Drayman needs to be installed using Getting started guide. Then install fs-extra library using this script:

npm install fs-extra @types/fs-extra

After Drayman is up and running and fs-extra is installed, replace home.tsx script as follows:

src/components/home.tsx
import { readJSON, writeJson, pathExists } from "fs-extra";
export const component: DraymanComponent = async ({ forceUpdate }) => {  const filePath = "./data.json";  let user: string;  const userList = (await pathExists(filePath)) ? await readJSON(filePath) : [];
  return () => {    return (      <>        <input          type="text"          value={user}          oninput={async ({ value }) => {            user = value;            await forceUpdate();          }}        />        <button          disabled={!user}          onclick={async () => {            userList.push(user);            await writeJson(filePath, userList);            user = null;            await forceUpdate();          }}        >          Add user        </button>        <ul>          {userList.map((x) => (            <li>{x}</li>          ))}        </ul>      </>    );  };};

After heading up to http://localhost:3033/ you will see two elements on page:

  • Input for user name.
  • Button which is disabled until some user name is entered and saves this name to database after it is clicked.

Let's input two names - "Alice", click a button, "Bob", click a button. You will immediately see a list of names below input and button. If you reload this page you will still see this list. That is because it was stored in your file system. You can now check contents of this file:

my-appโ””โ”€โ”€ data.json

If you check data.json contents you will see something similar to this:

data.json
["Alice","Bob"]

So now you have created a component which combines server-side and client-side code inside single script. In place of file system you can use any other database library which is available for Node.js, without separating client and server code.