10 Total.js features to use in your next Express.js application.

10 Total.js features to use in your next Express.js application.

Express.js is great. It has robust routing and a 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 fulfill 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 the total.js library that will change your life as a 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

NOSQL or TextDB is a text-based built-in database of Total.js. It is an awesome embedded database for your next node.js application. If you already know about SQLite, you probably understand what an embedded database is. But trust me, the main reason why you will prefer NOSQL to SQLite is that NOSQL is schema-free and faster and you do not need to install sqlite driver or install a third party ORM library to start using it. All what you need is run npm install total4 and then require('total4') Just like the example below:

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 files. Look into the picture.

Image

The content of each file looks like the following:

NOSQL is a must-try. Read more about it in docs.

2.UID/GUID

Unique identifiers are essential in programming. They are required in various cases like inserting new items into the database, creating random filenames, verification/confirmation tokens, etc. Total.js gives you awesome global functions to generate unique IDs: UID() and GUID().

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

Read more about UID here and GUID there.

3.RESTBuilder

Building modern applications today is a matter of design and architecture that can involve two or more applications talking to each other. RESTBuilder is a HTTP(S) client is carefully designed to make requesting other applications easy and comfortable. Example:

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 the documentation.

4.Image

This class contains functions to manipulate images. To start using Image, you need to have installed GraphicsMagick (recommended) or ImageMagick. Image is a global variable so you can call it from anywhere. Images are processed in an independent thread in order to guarantee some performance. Usage:

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

Output image

Image enables more other possibilities. Just click here to learn more.

5.SHELL

This function can allow the execution of shell commands. If you need to run some command lines on your server consider using the Total.js SHELL function. It is very easy.

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.

6.FILESTORAGE

File storage is awesome 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 recommend using UID that we discussed above. File storage makes it easy to store/read files, list, filter and remove like a pro (Yes just like in Google Drive). It offers quite useful 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:

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 but don't forget to leave a comment here about what you think about it.

7. TotalAPI

TotalAPI is a great service of Total Platform that allows you to give special features to your application, whether is a total.js application or not. You can use TotalAPI to send sms, print HTML to pdf, send emails, get geoip data, save logs data, get exchange rates, check VAT, etc at extremely low cost. You can even get free credits to test everything before.

  • Obtaining your API token. To start using you need to generate your API token at platform.totaljs.com. If you do not have an account yet, create your account and follow the next steps. Login into your account then open API services and then create a token.

    Total platfom dashboard

    You will be granted some free credits for testing. Then you click on buy credits to add more credits.

    otal platfom dashboard/Tokens

    You can now click on show token to copy your token for use in your code. You can use the .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 the code example) via sms with TotalAPI free credits☺️.

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

Good programmers always log application activities and you should consider doing the same. If you need a simple that does its jobs without slowing your application performance, then the Total.js LOGGER function is for you. It is easy to use and works very fine. It writes the message into the specified log file. The log file will contain the date + time automatically and you can include as much information as you want.

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

9.Utils

Utils is a global object of Total.js which contains lots of useful helper functions. Functions/methods can be accessed via Utils.fn_name() or U.fn_name() and you will find there, some useful 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.

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 recommend that you look into the documentation. Just click here.

10.Prototypes

Javascript Native objects such as String, Number, Array and Date can be extended thanks to prototypes. As soon as you include the 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 web server. Let us take an example with an Array prototype in an Express application that will run many workflows asynchronously using Array.async(fn);

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 the total.js documentation website to see more prototypes.

Total.js Documentation website

It has been a long way till the end of this post. It has never been easy to cover the universe of Total.js. There were 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's discuss it in the comments. And most important, write below in the comment which one of the Total.js feature you liked the most and why. Next, I will cover other features of the Total.js Client side. Yes, Total.js is full-stack which is why it is called Total.js. But before you go, consider following me here to not miss any posts about total.js. Thank you!

Did you find this article valuable?

Support Louis Bertson by becoming a sponsor. Any amount is appreciated!