How to run the same JavaScript function in browser and server?

0

I'm trying to use the TrackingJS library for face detection in an application. Currently my application using Multer uploads an image (I would like to do several, as I am using .single because it can not perform the detection by the local and server functions) just by returning and rendering the image that was sent in the Browser.

Here's my NodeJS.

//Pegando as variáves utilizadas na solicitação do módulo do NodeJS

const express = require('express'); //VARIÁVEIS APONTANDO PARA A PASTA NODE_MODULES E COLETANDO SEUS MÓDULOS
const multer = require('multer'); //QUE SÃO FUNÇÕES, AÇÕES ENTRE OUTROS QUE PODEM SER ACESSADOS PELA VARIÁVEL
const ejs = require('ejs'); //QUE RECEBE TODO A REFERÊNCIA (APONTANDO) PARA OS DIVERSOS PROCEDIMENTOS E 
const path = require('path'); // RECURSOS DOS SEUS RESPECTIVOS MÓDULOS.
const msg = require('./modtest');

//Acessar e usar um módulo para ENVIO DE ARQUIVOS através do protoco HTTP.


//Indicar o Engine de Armazenamento
const storage = multer.diskStorage({
    destination: './public/uploads/',
    filename: function(req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
});

// Init Upload
const upload = multer({
    storage: storage,
    limits: { fileSize: 4000000, files: 10 },
    fileFilter: function(req, file, cb) {
        checkFileType(file, cb);
    }
}).single('myImage');

// Check File Type
function checkFileType(file, cb) {
    // Allowed ext
    const filetypes = /jpeg|jpg|png|gif/;
    // Check ext
    const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
    // Check mime
    const mimetype = filetypes.test(file.mimetype);

    if (mimetype && extname) {
        return cb(null, true);
    } else {
        cb('Error: Images Only!');
    }
}

// Init app
const app = express();

// EJS
app.set('view engine', 'ejs');

// Public Folder
app.use(express.static('./public'));

app.get('/', (req, res) => res.render('index'));


app.post('/upload', (req, res) => {
    
    upload(req, res, (err) => {
        if (err) {
            res.render('index', {
                msg: err
            });
        } else {
            if (req.file == undefined) {
                res.render('index', {
                    msg: 'Nenhum Arquivo Selecionado!'
                });
            } else {
                res.render('index', {
                    
                    msg: 'Arquivo(s) Enviados' + req.file.filename,
                    file: 'uploads/${req.file.filename}',
                    
                });
                console.log('files', req.file);
            }
        }
    });
    
});


const port = 3035;

app.listen(port, () => console.log('Server started on port ${port} ${msg(7)}'));

My index.ejs is this:

<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>DETECTA</title>
    <link rel="manifest" href="../../manifest.json">
    <link rel="stylesheet" href="./css/style.css">
    <link rel="stylesheet" href="./css/custom.css">
    <link rel="stylesheet" href="./css/materialize.css">
    <link rel="stylesheet" href="./css/sweetalert.css">
    <link rel="stylesheet" href="./css/materialdesignicons.css" media="all"/>
    
   
 <!-- CHAMADA SERVICE WORKER-->
    <script>
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('../../sw.js')
                .then(function() {
                    console.log('service worker registered');
                })
                .catch(function() {
                    console.warn('service worker failed');
                });
        }
    </script>
    
</head>

<body>

<header>



<!-- PROCESSAR IMAGEM - Contém a coleta das informações sobre os arquivos a serem processados-->

    <h3 class="center">Detecção de Faces</h3>
    <p id="imgvalor"></p>
    <div class="row col s6 offset-s4 center ajuste">
        
        <%= typeof msg != 'undefined' ? msg : '' %>
        
        <form action="/upload" method="POST" enctype="multipart/form-data">
              <div class="file-field input-field offset-s4">
              <div class="btn gradient-45deg-blue-indigo">
              <span  id="total" >Arquivo(s)</span>
              <input type="file" id="file" name="Imagem" /></div>
                <div class="file-path-wrapper">
                    <input id="fileUpload" class="file-path validate" type="text" placeholder="Escolha um ou mais imagens">
                </div>
                </div>
            <button class="btn btn-success waves-effect waves-light gradient-45deg-blue-indigo" id="enviar" type="submit" name="action">Enviar<i class="mdi mdi-send left"></i>
            </button>    
        </form>
        <br>
                
        <div id="list"></div>
                <img src="<%= typeof file != 'undefined' ? file : ''%>" class="responsive-img" alt="">

    




    <script src="./js/battery.js" async></script>
    <script src="./js/core.js" async></script>
    <script src="./js/network.js" async></script>
    <script src="./js/tarefa.js" async></script>
    <script src="./js/sweetalert.min.js"></script>
    
    <!-- Scripts que desejo executar no browser e no servidor
    
    <script src="./js/tracking-min.js"></script>
    <script src="./js/face-min.js"></script>
    
    -->

    <script src="./js/jquery-3.2.1.min.js"  
            integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
            crossorigin="anonymous">
    </script>

    <script src="./js/materialize.js"></script>

   

    <script>
    //Gostaria que essa chamada estivesse atrelada ao botão de envio para a função local ou no servidor, a depender do botão. e no servidor ela me retornasse ou a imagem já rastreda ou o array.
window.onload = function() {
      var img = document.getElementById('img');
      var tracker = new tracking.ObjectTracker(['face']);
      tracker.setStepSize(1.7);
      tracking.track('#img', tracker);
      var face = [];
      var i = 0;
      tracker.on('track', function(event) {
        event.data.forEach(function(rect) {
          window.plot(rect.x, rect.y, rect.width, rect.height);
          i++;
          face[i] = rect.x + '-' +rect.y;
       
        });
        alert(face);
        document.getElementById('cont').innerHTML = i;
      });
      window.plot = function(x, y, w, h) {
        var rect = document.createElement('div');
        document.querySelector('.demo-container').appendChild(rect);
        rect.classList.add('rect');
        rect.style.width = w + 'px';
        rect.style.height = h + 'px';
        rect.style.left = (img.offsetLeft + x) + 'px';
        rect.style.top = (img.offsetTop + y) + 'px';
      };
      
    };

    
  </script>



</body>

</html>

How can I call this local function and server? And if at all possible, how can I measure its execution time when running locally and on the server? Thank you.

    
asked by anonymous 01.03.2018 / 04:28

0 answers