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
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:
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.
The content of each file looks like 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 database, creating random filenames, verification/confirmation token, etc. Total.js gives you awsome 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');
})
Read more about UID here and GUID there.
3.RESTBuilder
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:
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.
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 that you can call it from anywhere. Images are processed in an independent thread in order to guarantee some perfermance. 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');
});
Image enables more other possibilities. Just click here to learn more.
5.SHELL
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.
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 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:
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 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. You will be granted some free credits for testing. Then you click on buy credits to add more credits. 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☺️.
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 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.
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
9.Utils
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.
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.
10.Prototypes
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)
;
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 to see more protoypes.
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!
Top comments (0)