Ausnahme gefangen: SSL certificate problem: certificate is not yet valid 📌 10 Total.js features to use in your next Express.js application.

🏠 Team IT Security News

TSecurity.de ist eine Online-Plattform, die sich auf die Bereitstellung von Informationen,alle 15 Minuten neuste Nachrichten, Bildungsressourcen und Dienstleistungen rund um das Thema IT-Sicherheit spezialisiert hat.
Ob es sich um aktuelle Nachrichten, Fachartikel, Blogbeiträge, Webinare, Tutorials, oder Tipps & Tricks handelt, TSecurity.de bietet seinen Nutzern einen umfassenden Überblick über die wichtigsten Aspekte der IT-Sicherheit in einer sich ständig verändernden digitalen Welt.

16.12.2023 - TIP: Wer den Cookie Consent Banner akzeptiert, kann z.B. von Englisch nach Deutsch übersetzen, erst Englisch auswählen dann wieder Deutsch!

Google Android Playstore Download Button für Team IT Security



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


💡 Newskategorie: Programmierung
🔗 Quelle: dev.to

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.
Image
The content of each file looks like following:
Nosql file content
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');
})

UID output
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');
});

Input image
Output image
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. 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 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
Logger 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.
Total.js Documentation website
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!

...



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


📈 47.99 Punkte

📌 Extend your desktop application with Windows 10 features using the new Visual Studio Application Packaging Project


📈 21.89 Punkte

📌 Cisco Mobility Express 2800/Mobility Express 3800 8.2(130.0) 802.11 Ingress Packet Denial of Service


📈 21.69 Punkte

📌 Cisco Mobility Express: Eine Schwachstelle in Cisco Mobility Express ermöglicht Übernahme eines Systems


📈 21.69 Punkte

📌 Adafruit’s Circuit Playground Express simulated Visual Studio Code’s Device Simulator Express


📈 21.69 Punkte

📌 Medium CVE-2020-7616: Express-mock-middleware project Express-mock-middleware


📈 21.69 Punkte

📌 Cisco Mobility Express 2800/Mobility Express 3800 8.2(130.0) 802.11 Ingress Packet denial of service


📈 21.69 Punkte

📌 High CVE-2020-29579: Express-gateway Express-gateway docker


📈 21.69 Punkte

📌 Medium CVE-2020-24391: Mongo-express project Mongo-express


📈 21.69 Punkte

📌 Cisco Mobility Express 2800/Mobility Express 3800 8.2(130.0) 802.11 Ingress Packet Denial of Service


📈 21.69 Punkte

📌 AV-Comparatives : Total Cost of Ownership Report für Endpoint Protection ... - Börse Express


📈 21.26 Punkte

📌 Total War: Three Kingdoms im Test - Das beste Total War seit Jahren! (aber nicht für jeden)


📈 20.84 Punkte

📌 Games - "Total War: Three Kingdoms" begeistert bei ersten Tests: "Das bisher beste 'Total War'"


📈 20.84 Punkte

📌 Kaspersky Total Security: Kaspersky Total Security – Vielfach ausgezeichneter Online-Schutz zum Sonderpreis


📈 20.84 Punkte

📌 What Is Linux Kernel Keystore and Why You Should Use It in Your Next Application


📈 20.63 Punkte

📌 Unlock Next-Level Authentication in Next.js with Next Auth and TypeScript Module Augmentation


📈 19.05 Punkte

📌 CVE-2023-45886 | F5 BIG-IP/BIG-IP Next/BIG-IP Next SPK/BIG-IP Next CNF ZebOS BGP denial of service (K000137315)


📈 19.05 Punkte

📌 How to Use Comenity EasyPay for Your Bills: Comenity Easy Pay Express Login


📈 18.98 Punkte

📌 Application News – Application Security Weekly #58 Application Security Weekly #58


📈 18.43 Punkte

📌 Application News – Application Security Weekly #58 Application Security Weekly #58


📈 18.43 Punkte

📌 AI can write your emails, reports, and essays. But can it express your emotions? Should it?


📈 17.86 Punkte

📌 Embracing Your Coding Style: How Do You Express Your Individuality in a Tech Career?


📈 17.86 Punkte

📌 Does Your Cyber Liability Insurance Fit with Your Total Insurance Coverage?


📈 17.43 Punkte

📌 creating a next.js front end with a express backend using typescript


📈 17.19 Punkte

📌 Next.js vs. Express.js: What Are the Differences?


📈 17.19 Punkte

📌 Use Next.js, Tailwind CSS, and MongoDB to Build a Ticketing Application


📈 17.12 Punkte

📌 Next.js vs. Angular: Comparing key features and use cases


📈 17.08 Punkte

📌 Medium CVE-2018-2699: Oracle Application express


📈 16.99 Punkte

📌 Oracle APEX 1.5.0/1.6.1 Application Express unknown vulnerability


📈 16.99 Punkte











matomo