Advertisement
Guest User

Untitled

a guest
Oct 2nd, 2017
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const chokidar = require('chokidar');
  2. const mysql = require('mysql');
  3. const path = './web/files/clientes/**/*.csv';
  4.  
  5. let watcher = chokidar.watch(path, {
  6.     ignored : /[\/\\]\./,
  7.     persistent : true
  8. });
  9.  
  10. console.log('>> Ouvindo alterações no diretório: ' + path);
  11.  
  12. watcher.on('change', (path) => {
  13.     let splitPath = path.split('/');
  14.     let cpfCnpj = splitPath[3];
  15.     let fileName = splitPath[4];
  16.  
  17.     console.log("CPF/CNPJ: " + cpfCnpj, "CSV: " + fileName);
  18.  
  19.     let mySqlConnection = mysql.createConnection({
  20.         host : "localhost",
  21.         port : 3306,
  22.         user : "root",
  23.         password : "123456",
  24.         database : "imobbi"
  25.     });
  26.  
  27.     mySqlConnection.connect((err) => {
  28.         if (err) {
  29.             throw err
  30.         }
  31.  
  32.         let sqlCliente = "SELECT `id` FROM `clientes` WHERE `cnpj` = " + cpfCnpj;
  33.  
  34.         mySqlConnection.query(sqlCliente, (error, results, fields) => {
  35.             if (error) {
  36.                 return console.log(error);
  37.             }
  38.  
  39.             if (!results[0]) {
  40.                 return console.log('Cliente com CPF/CNPJ ' + cpfCnpj + ' não encontrado.');
  41.             }
  42.  
  43.             let clienteId = parseInt(results[0].id);
  44.  
  45.             let sqlCsv = `
  46.                 UPDATE \`csv\` SET \`sincronizado\` = 0, \`sincronizado_data\` = NOW()
  47.                 WHERE \`clientes_id\` = ${clienteId}
  48.                 AND \`arquivo\` = "${fileName}"
  49.             `;
  50.  
  51.             mySqlConnection.query(sqlCsv, (error, results, fields) => {
  52.                 if (error) {
  53.                     return console.log(error);
  54.                 }
  55.  
  56.                 console.log('CSV atualizado!');
  57.             });
  58.         });
  59.  
  60.         console.log("MySQL Connected! =D");
  61.     });
  62. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement