Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript node module.exports / require() code on the front-end

I've been looking into using a library such as SVGO to be able to clean user submitted SVG code on the front end. SVGO is a node.js based library which typically works on the back end, so I've been trying to wrap my head around how to go about sending SVG code from the front end to the back end and then have the cleaned code regurgitated on the front end.

It's when I was trying to figure this out that I checked their web app example, which—upon inspection, runs code inside linked scripts that I would typically see on the back end on the front end. In particular, many of their functions have the signature (full script):

1: [function(require, module, exports) {
    "use strict";
    var loadScripts = require("./load-scripts"),
    ...
module.exports = exportedFunction;
}]

Pretty confusing, as this is typically JS that I've associated with the backend, particularly the require, module.exports syntaxes to name a few.

Question

  1. Is this simply their entire library, SVGO, on the front end? Did they manually rewrite it to be compatible with the front end? Or is that what tools like browserfy are for?
  2. If so, what are the benefits of running it on the front end vs on the back end? Would one be easier/are there some common guidelines on which to use where?
  3. From initial glance, it seems that it would be easier to just run the SVGO library in browser and do my conversion there (as I wouldn't have to make a call to the back end). What is the general practice there?

Thanks for any insight. I'm trying to make sure I build my project in the way that makes most sense/up to web standards.

like image 338
nikk wong Avatar asked Jun 17 '15 08:06

nikk wong


1 Answers

Answers:

  1. They are using module loaders like browserify or requirejs to allow the use of commonjs modules in the browser. It doesn't mean all the library would work on the client side, using node io modules would not work for example.

  2. It can be useful to make some cleanup on the browser side before sending (saving a few kBytes). Browser has the advantage to be free, you don't pay for hosting the code that run on the client side, some optionnal sanitization can be run on the browser. But: see 3.

  3. Even if it is easy to make client-side sanitization, you should always check and sanitize user's inputs on the backend, especially .svg files as they can contain <script> tags that might allow XSS .

like image 100
n00dl3 Avatar answered Nov 14 '22 22:11

n00dl3