10 Total.js features to use in your next Express.js application.
Tags: javascript, node, express, totaljs
Published: 2023-02-23 01:30:36

Express.js is great. It has robust routing and strong middleware system that makes it easy to build server side applications on top of node.js. However server side application development generally requires many other things like generating unique IDs and communication with databases, requesting external applications, handling uploaded files, logging, OS level system calls, consuming cloud API services, string operations, handling complex datetime objects and much more. To fullfill all those requirements, 100% of express developers and node.js developers in general always have to look beyond Express.js. Today i am revealing at least 10 features of total.js library that will change your life of Node.js developer:

- __NOSQL/TextDB__
- __UID/GUID__
- __RESTBuilder__
- __Image__
- __SHELL__
- __FILESTORAGE__
- __TotalAPI__
- __LOGGER__
- __Utils__
- __Prototypes__

Yes, total.js is amazing! Total.js Framework is a collection of javascript libraries and tools for building modern and next generation web applications. Let’s jump right then into discovery.
## [1.NOSQL](https://docs.totaljs.com/total4/62ba4001tf51c/)
NOSQL or TextDB is a text based built-in database of Total.js. It is the awsome embedded database for your next node.js application. If you already know about SQLITE, you probably understand what embedded database is. But trust me, the main reason why you will prefer NOSQL to SQLite is that NOSQL is schema free, faster and you do not need to install sqlite driver or install third party ORM library to start using it. All what you need is run `npm install total4` and then `require('total4')` Just like the examble below:
```js
const Express = require('express');
require('total4');

const app = Express();


app.get('/', function(req, res) {
    res.send('Hello world');
});

app.get('/users/insert', function(req, res) {
    var user1 = FAKE({ id: UID, name: String, firstname: 'Name(30)', lastname: 'Name(30)', age: Number, dtcreated: Date });
    NOSQL('users').insert(user1).callback(function(err, response) {
        if (err) {
            errorHandler(err, res);
            return;
        } else
            res.send('Success!')
    });

});

app.get('/users/insert', function(req, res) {
    var user2 = FAKE({ id: UID, name: String, firstname: 'Name(30)', lastname: 'Name(30)', age: Number, dtcreated: Date });
    NOSQL('users').insert(user2).callback(function(err, response) {
        if (err) {
            errorHandler(err, res);
            return;
        } else
            res.json(response);
    });
});

app.get('/users/list', function(req, res) {
    NOSQL('users').find().callback(function(err, response) {
        if (err) {
            errorHandler(err, res);
            return;
        } else
            res.json(response);
        
    });
});

app.get('/users/read/:id', function(req, res) {
    NOSQL('users').one().where('id', req.params.id).callback(function(err, response) {
        if (err) {
            errorHandler(err, res);
            return;
        } else
            res.json(response);
    });
});

app.get('/users/update/:id', function(req, res) {
    NOSQL('users').update({ position: 'Head of Developement' }).where('id', req.params.id).callback(function(err, response) {
        if (err) {
            errorHandler(err, res);
            return;
        } else
            res.json(response);
    });
});

app.get('/users/remove/:id', function(req, res) {
    NOSQL('users').remove().where('id', req.params.id).callback(function(err, response) {
        if (err) {
            errorHandler(err, res);
            return;
        } else
            res.json(response);
    });
});

var errorHandler = function(err, res) {
    res.status(500).json({ success: false, error: err || 'Something went wrong!' });
}


app.listen(8000, function() {
    console.log('Express server is listening');
});
```
Good to know: Nosql will create a folder called databases at the root of your application and create some .nosql file. Look into picture.
![Image](https://miro.medium.com/v2/resize:fit:440/format:webp/1*rnYdJnLnkkiDlrak_gxi_w.png)
The content of each file looks like following:
![Nosql file content](https://miro.medium.com/v2/resize:fit:1400/format:webp/1*02hZIR-2VAXG9Ev5Z_QtSA.png)
NOSQL is a must-try. Read more about it in [docs](https://docs.totaljs.com/total4/62ba4001tf51c/).
## [2.UID/GUID](https://docs.totaljs.com/total4/407ff001jy51c/#49a0b001cl51c)
Unique identifiers are essential in programming. They are required in various cases like inserting new items into database, creating random filenames, verification/confirmation token, etc. Total.js gives you awsome global functions to generate unique IDs: `UID()` and `GUID()`.

```js
const Express = require('express');
require('total4');

const app = Express();

app.get('/', function(req, res) {
    var uid = UID();
    var guid = GUID(80);
    res.json({ short: uid, long: guid });
});


app.listen(8000, function() {
    console.log('Express server is listening');
})
```
![UID output](https://miro.medium.com/v2/resize:fit:1400/format:webp/1*-AhG5tIqoeWfce4ff0hnvg.png)
Read more about UID [here](https://docs.totaljs.com/total4/407ff001jy51c/#4ab23001xr51c) and GUID [there](https://docs.totaljs.com/total4/407ff001jy51c/#49a0b001cl51c).


## [3.RESTBuilder](https://docs.totaljs.com/total4/62546001dd51c/)
Building modern applications today is a matter of design and architectures that can involve two or more applications to talk to each other. __RESTBuilder__ is a `HTTP(S)` client carefully designed to make requesting other applications easily and comfortably. Example:
```js
const Express = require('express');
require('total4');

const app = Express();
var url = 'https://jsonplaceholder.typicode.com';

app.get('/', function(req, res) {
   
    RESTBuilder.GET(url + '/posts').callback(function (err, response, meta) {
        if (err) 
            res.status(500).json({ success: false, error: err });
        else
            res.json(response);

    });
});


app.get('/photos', async function(req, res) {
   var photos = await RESTBuilder.GET(url + '/photos').promise();
   res.json(photos);
});

app.listen(8000, function() {
    console.log('Express server is listening');
});
```
However __RESTBuilder__ has a complete collection of methods to execute HTTP(S) advanced requests. Discover more in [documentation](https://docs.totaljs.com/total4/62546001dd51c/).
## [4.Image](https://docs.totaljs.com/total4/4047d004kk50c/)
This class contains functions to manipulate images. To start using __Image__, you need to have installed [GraphicsMagick](http://www.graphicsmagick.org/) (recommended) or [ImageMagick](https://imagemagick.org/index.php). __Image__ is a global variable so that you can call it from anywhere. Images are processed in an independent thread in order to guarantee some perfermance. Usage:
```js
const Express = require('express');
require('total4');

const app = Express();
app.get('/', function(req, res) {
    var image = Image.load(F.Fs.createReadStream('/home/louisbertson/Desktop/meme.jpg'));
    // image.resizeCenter(200, 200); resizecenter image
    image.grayscale(); // grayscale image

    var filename = PATH.root('output.jpg'); // PATH is part of total.js

    image.save(filename); 
    res.send('Success');
});

app.listen(8000, function() {
    console.log('Express server is listening');
});
```
![Input image](https://miro.medium.com/v2/resize:fit:720/format:webp/1*mFoZEw_YjlI0i0HnNPpjEA.jpeg)
![Output image](https://miro.medium.com/v2/resize:fit:720/format:webp/1*jXcCHfgFSSWXONbh_qho3A.jpeg)
Image enables more other possibilities. Just click here to learn more.
## [5.SHELL](https://docs.totaljs.com/total4/407ff001jy51c/#p3un001kt41d)
This function can allow executing shell command.
If you need to run some command lines on your server consider using Total.js SHELL function. It is very easy.
```js
const Express = require('express');
require('total4');

const app = Express();

app.get('/', function(req, res) {
    SHELL('uptime -p', function(err, response) {
        if (err)
            res.status(500).json({success: false, error: err});
        else
            res.json({ success:true, value: response });
    });
});

app.get('/ping', function(req, res) {
    SHELL('ping -c 3 {0}'.format(req.query.host), function(err, response) {
        if (err)
            res.status(500).json({success: false, error: err});
        else
            res.json({ success:true, value: response.split('\n') });
    });
});


app.listen(8000, function() {
    console.log('Express server is listening');
});
```
If you wish to learn more about SHELL, take a look into its [documentation](https://docs.totaljs.com/total4/407ff001jy51c/#p3un001kt41d).
## [6.FILESTORAGE](https://docs.totaljs.com/total4/40d59001ti51c/)
File storage is awsome too. It is used to store and handle uploaded files of your application according to unique IDs. Unique IDs can be anything else but we recommand using UID that we discussed about above.
File storage make it easy to store/read files, list, filter and remove like a pro (Yes just like in Google Drive). It offers quiet usefull features and can also be used as the missing file manager of `multer` in express world.
Unfortunately we cannot cover everything here, but i hope you will look into its documentation, play with it, and leave us comments here about what you think about it.
In this example i am using File Storage next to `multer` in an `express.js` application:
```js
const Express = require('express');
const multer  = require('multer');
require('total4');
var Storage = FILESTORAGE('files');

const upload = multer({ 
    dest: 'uploads/',
    filename: function (req, file, cb) {
        let extension = file.mimetype.split('/')[-1];
        cb(null, file.fieldname + '-' + Date.now()+ '.' + extension)
      }
});

const app = Express();

app.post('/upload', upload.single('file'), function (req, res) {
    var file = req.file;
   
    var id = UID();
    Storage.save(id, file.originalname, file.path, function(err, meta) {
        if (err)
            res.status(500).json({ success: false, error: err });
        else {
            PATH.unlink(file.path); // PATH is part of total.js too.
            res.json({ success: true, value: meta });
        }
    });
});

app.get('/files', function(req, res) {
    Storage.browse().callback(function(err, response) {
        if (err)
            res.status(500).json({ success: false, error: err });
        else
            res.json({ success: true, value: response });
    });
});

app.get('/files/read/:id', function(req, res) {
    Storage.read(req.params.id, function(err, response) {
        if (err)
            res.status(500).json({ success: false, error: err });
        else
            res.json({ success: true, value: response });
    }, true);
});

app.post('/files/rename/:id', function(req, res) {
    Storage.rename(req.params.id, req.body.newname, function(err, response) {
        if (err)
            res.status(500).json({ success: false, error: err });
        else
            res.json({ success: true, value: response });
    });
});

app.get('/files/remove/:id', function(req, res) {
    Storage.remove(req.params.id, function(err, response) {
        if (err)
            res.status(500).json({ success: false, error: err });
        else
            res.json({ success: true, value: response });
    });
});

app.get('/download/:id', function(req, res) {
    Storage.read(req.params.id, function(err, response) {
        response.stream.pipe(res);
    });
});

app.listen(8000, function() {
    console.log('Express server is listening');
});
```
Now can build your own Google drive with it, just read more into [documentation](https://docs.totaljs.com/total4/40d59001ti51c/) but don't forget to leave a comment here about what you think about it.
## [7. TotalAPI](https://docs.totaljs.com/totalapi/)
__TotalAPI__ is a great service of __Total Platform__ that allows you give special features to your application, whether is total.js application or not. You can use TotalAPI to send sms, print html to pdf, send mails, get geoip data, save logs data, get exchange rates, check VAT, etc at extremely low cost. You can even get __free credits__ to test everithing before.
- __Obtaining your API token.__
To start using you need to generate your api token at platform.totaljs.com.
If you do not have account yet, create your account and follow the next steps.
Login into your account then open __API services__, and then __create token__.
![Total platfom dashboard](https://cdn-images-1.medium.com/max/800/1*TJJCSahKTK97_YQWNwcbew.png)
You will be granted some __free credits__ for testing. Then you click on __buy credits__ to add more credits.
![otal platfom dashboard/Tokens](https://cdn-images-1.medium.com/max/800/1*F0_bnjb1nKcMIP4hwpuNkA.png)
You can now click on __show token__ to copy your token for using in your code.
You can use .env file to store your token but in the following example we are using it in a simple variable. Copy/paste the following code to send
a comment to us (Phone number in code example) via sms with TotalAPI free credits☺️.
```js
const Express = require('express');
require('total4');
var token = ''; // Your token here
var name = ''; // Your full name here
var message = ''; // Your comment/message here
const app = Express();

app.get('/send/sms', function (req, res) {
    TotalAPI(token, 'sms', { from: name, to: '+421903163302', body: message }, function(err, response) {
        if (err)
            res.status(500).json({ success: false, error: err });
        else
            res.json({ success: true, value: response });
    });
});

app.get('/check', function (req, res) {
    TotalAPI(token, 'check', {}, function(err, response) {
        if (err)
            res.status(500).json({ success: false, error: err });
        else
            res.json({ success: true, value: response });
    });
});

app.listen(8000, function() {
    console.log('Express server is listening');
});
```
## [8.LOGGER](https://docs.totaljs.com/total4/407ff001jy51c/#49a5b001py51c)
Good programmers always log application activities and you should consider doing the same. If you need simple that does its jobs without slowing doing your application performance, then __Total.js LOGGER__ function is for you. It is easy to use and works very fine. It writes the message into the specific log file. The log file will contain date + time automatically and you can include as much information as you want.
```js
const Express = require('express');
require('total4');

const app = Express();

app.get('/log', function (req, res) {

    LOGGER('app', req.path, { name: 'Test logs' }, { name: 'Another test logs' });
    res.send('success');
});

app.listen(8000, function() {
    console.log('Express server is listening');
});
```
This will write logs in __/logs/app.log__ file
![Logger file](https://cdn-images-1.medium.com/max/800/1*txiaM4mHwFA7A3__U8JAdw.png)
## [9.Utils](https://docs.totaljs.com/total4/4047d002kk50c/)
Utils is a global object of __Total.js__ which contains lots of usefull helper functions. Functions/methods can be accessed via `Utils.fn_name()` or `U.fn_name()` and you will find there usefull things like `U.parseXML()`
, `U.random([min], [max])` , `U.reader()` , `U.queue()` , etc.
let us take an example with `U.resolve()` to resolve any IP address from DNS.
```js
const Express = require('express');
require('total4');

const app = Express();

app.get('/dns/resolve', function(req, res) {
    U.resolve(req.query.host || 'http://google.com', function(err, response) {
        console.log(response);
        if (err)
            res.status(500).json({ success: false, error: err });
        else
            res.json({ success: true, value: response });
    } );
});

app.get('/random', function(req, res) {
    res.json({ success: true, value: U.random(10, 999) });
}); 

app.listen(8000, function() {
    console.log('Express server is listening');
});
```
We cannot cover everything in this blog post. I recommand that you look into documentation. Just click [here](https://docs.totaljs.com/total4/4047d002kk50c/).
## [10.Prototypes](https://docs.totaljs.com/total4/4047f003ge51c/#4b70d001xm51c)
Javacript Native objects such as String, Number, Array and Date can be extended thanks to prototypes. As soon as you include express.js project via `require('total4')` , those Obect are extended with great features.
Everything become accessible: If you need a slug from a String you don't need extra library. Just use `String.slug()`. 
E.g : `console.log('Hello world'.slug()) // output: hello-world` 
 And there are prototypes for many objects by total.js even the Node.js Request and Response objects. In this case you need to use total.js as webserver. 
Let us take an example with Array prototype in an Express application
that will run many workflows asynchronously using `Array.async(fn)`;
```js
const Express = require('express');
require('total4');

const app = Express();

app.get('/workflows', function(req, res) {
   var arr = [];

   arr.push(function(next) {
        console.log('Task 1');
        next();
   });

   arr.push(function(next) {
        console.log('Task 2');
        next();
   });

   arr.push(function(next) {
        console.log('Task 3');
        next();
   });

   arr.push(function(next) {
        console.log('Task 4');
        next();
   });

   arr.push(function(next) {
        console.log('Task 5');
        next();
   });

   arr.push(function(next) {
        console.log('Task 6');
        next();
   });

   arr.async(function() {
        console.log('Done!');
        res.json({ success: true, value: 'Done' });
   });
});

app.listen(8000, function() {
    console.log('Express server is listening');
});
```

You can visit total.js [documentation website](https://docs.totaljs.com) to see more protoypes.
![Total.js Documentation website](https://cdn-images-1.medium.com/max/800/1*h25VHoe0TXP6W43fPmOtXg.png)
It has been a long way till the end of this post. It has never been easy to cover all the universe of Total.js. There was a 10 features of total.js to discover for your next Node.js/Express application. I hope you enjoyed the reading. If any part of this blog post is not clear, let'us discuss about it in comments. And most important, write below in comment which one of Total.js feature you liked the most and why. 
Next, i will cover other features of Total.js Client side. Yes Total.js fullstack that is why it is called Total.js . But before you go, consider following me here to not miss any post about total.js. I Thank you!