# Watcher for NodeJS

## What are Watchers for NodeJS?

Watcher for NodeJS are modules or tools that allow developers to monitor changes in files or directories and execute code in response to those changes.

NodeJS provides a built-in module called "fs" (file system) that allows developers to interact with the file system. Watchers for NodeJS use the "fs" module to monitor changes in files or directories by continuously checking for modifications, deletions, and additions.

Read below to learn how to use Watcher for NodeJS with Filebase.

{% hint style="success" %}

## Prerequisites:

* [x] [Install Node.js and npm](https://nodejs.org/en/download/).
* [x] Download and install an IDE of your choice, such as [VSCode](https://code.visualstudio.com/).
* [x] [Sign up](https://filebase.com/signup) for a free Filebase account.
* [x] Have your Filebase Access and Secret Keys. Learn how to view your access keys [here](https://docs.filebase.com/getting-started-guides/getting-started-guide#working-with-access-keys).
  {% endhint %}

### **1. First, we need a Filebase IPFS bucket.**

To do this, navigate to [console.filebase.com](https://console.filebase.com/). If you don’t have an account already, [sign up](http://filebase.com/signup), then log in.

### **2. Select ‘Buckets’ from the left sidebar menu, or navigate to** [**console.filebase.com/buckets**](http://console.filebase.com/buckets)**.**

Select ‘Create Bucket’ in the top right corner to create a new bucket.

<figure><img src="https://3861818989-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lyjw7dWpiQtUFDa1pO0%2Fuploads%2FacnEsFe26Y510Thqb2ES%2Fimage.png?alt=media&#x26;token=7e6e7cac-8d98-4f95-b5c0-13877b78b056" alt=""><figcaption></figcaption></figure>

### **3. Enter a bucket name and choose the IPFS storage network to create the bucket.**

{% hint style="info" %}
Bucket names must be unique across all Filebase users, be between 3 and 63 characters long, and can contain only lowercase characters, numbers, and dashes.
{% endhint %}

<figure><img src="https://3861818989-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lyjw7dWpiQtUFDa1pO0%2Fuploads%2FHyHSqkHxnnpLJYG0kNVx%2Fimage.png?alt=media&#x26;token=01cbb4de-4371-4361-8217-f556bcd1a9e6" alt=""><figcaption></figcaption></figure>

### **4. Next,** [**download and install**](https://github.com/s3fs-fuse/s3fs-fuse) **S3FS-FUSE on a Linux or macOS system.**

### **5. Set up an Access Key file for use with S3FS-FUSE.**

Set up a credentials file for S3FS at `${HOME}/.passwd-s3fs`. You will need to save your Filebase Access and Secret keys to this file and give it owner permissions. You can do so with the following commands:

`echo ACCESS_KEY_ID:SECRET_ACCESS_KEY > ${HOME}/.passwd-s3fs`

`chmod 600 ${HOME}/.passwd-s3fs`

**ACCESS\_KEY\_ID** is your Filebase Access key, and **SECRET\_ACCESS\_KEY** is your Filebase Secret key. For more information on Filebase access keys, see [here](https://docs.filebase.com/getting-started-guides/getting-started-guide#working-with-access-keys).

### **6. Mount your bucket.**

You can mount a Filebase IPFS bucket with the command:

`s3fs mybucket /path/to/mountpoint -o passwd_file=${HOME}/.passwd-s3fs -o url=https://s3.filebase.com`

* **mybucket:** name of your Filebase bucket

### 7. Next, install the following packages:

`npm install chokidar fs-extra`

### 8. Next, create the following directory structure:

<figure><img src="https://3861818989-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lyjw7dWpiQtUFDa1pO0%2Fuploads%2FYTOn5zXaCB0nadZ6oUcb%2Fimage.png?alt=media&#x26;token=ae238bc6-68a9-4f6c-9f58-f2aed3dfa5e4" alt=""><figcaption></figcaption></figure>

### 9. In the services directory, create a new file called `observer.js`.

Insert the following code into this file:

```jsx
const chokidar = require('chokidar');
const EventEmitter = require('events').EventEmitter;
const fsExtra = require('fs-extra');

class Observer extends EventEmitter {
  constructor() {
    super();
  }

  watchFolder(folder) {
    try {
      console.log(
        `[${new Date().toLocaleString()}] Watching for folder changes on: ${folder}`
      );

      var watcher = chokidar.watch(folder, { persistent: true });

      watcher.on('add', async filePath => {
        if (filePath.includes('error.log')) {
          console.log(
            `[${new Date().toLocaleString()}] ${filePath} has been added.`
          );

          // Read content of new file
          var fileContent = await fsExtra.readFile(filePath);

          // emit an event when new file has been added
          this.emit('file-added', {
            message: fileContent.toString()
          });

          // remove file error.log
          await fsExtra.unlink(filePath);
          console.log(
            `[${new Date().toLocaleString()}] ${filePath} has been removed.`
          );
        }
      });
    } catch (error) {
      console.log(error);
    }
  }
}

module.exports = Observer;
```

### 10. Then, create a new file called `server.js` that contains the following code:

```jsx
const Obserser = require('./services/observer');

var obserser = new Obserser();

const folder = '/path/to/watch';

obserser.on('file-added', log => {
  // print error message to console
  console.log(log.message);
});

obserser.watchFolder(folder);
```

Replace `/path/to/watch` with the file path of your mounted Filebase bucket.

### 11. Then, in the project’s root directory, run the following command:

`node src/server.js`

### 12. Now, move a folder or file into your mounted Filebase bucket directory.

The move will be logged by the watcher script:

`[2/21/2023, 11:01:51 AM] Watching for folder changes on: /Users/jessiemongeon/filebase-bucket`

`[2/21/2023, 11:01:51 AM] /Users/jessiemongeon/filebase-bucket/image.png has been added.`
