Detectar coordenada de imagem na tela NodeJS

Tenho muitas tarefas repetitivas e chatas de fazer, pra isso eu uso o AutoIT, com esse script pra procurar uma imagem na tela: https://www.autoitscript.com/forum/topic/148005-imagesearch-usage-explanation/

#include <ImageSearch.au3>  HotKeySet("p", "checkForImage")  global $  y = 0, $  x = 0  Func checkForImage() local $  search = _ImageSearchArea('check5.bmp', 1, 800, 40, 900, 80, $  x, $  y, 0) If $  search = 1 Then MouseMove($  x, $  y, 10) EndIf EndFunc  while 1 sleep(200) WEnd 

Ele fica escaneando uma área da tela, e se encontrar uma imagem ele move o mouse pra essa imagem

Gostaria de saber se tem alguma ferramenta pra fazer isso no NodeJS… Eu vi sobre opencv4nodejs https://www.npmjs.com/package/opencv4nodejs

Ele reconhece imagem na tela com webcam, cria quadrados na tela, lib louca pra caramba, mas não achei nada relacionado a procurar por uma imagem na tela com ele no node, isso é possivel? ou tem outra ferramenta melhor que serve pra isso?

Selecionar HASH Code SHA256 NodeJS

Como eu faço pra selecionar o código pra HASH no NodeJS?

Eu tenho um sistema feito em outra linguagem com senhas encryptadas com SHA256

A função de encryptação lá é assim:

#define HASH_CODE = 'WEASDSAEWEWAEAWEAWEWA'; SHA256_PassHash(HASH_CODE, password, 64); 

Primeiro parametro é o código da HASH, o segundo é o valor a ser encryptado e o terceiro é a base64

Consegui fazer encryptação no NodeJS, mas não tenho controle do código da HASH, então os sistemas não criam a mesma HASH, como eu faço pra selecionar o código da HASH ao registrar no NodeJS para que ele possa se comunicar com esse outro sistema?

const code = 'WEASDSAEWEWAEAWEAWEWA'; const normal = 'anne'; const crypto = require('crypto'); const encryptado = crypto     .createHash('sha256')     .update(normal)     .digest('base64'); console.log(encryptado); 

Relacionamento entre models com Nodejs e MongoDB

Venho de uma bagagem de banco de dados relacionais, porém, agora utilizando MongoDB notei que não existe JOIN, alguém poderia me instruir em como criar essa consulta ?

Possuo três models: model Client, model Transaction que possui o campo clientId, model Payables que possui o campo transactionId.

model Client inserir a descrição da imagem aqui

model Transaction inserir a descrição da imagem aqui

model Payable inserir a descrição da imagem aqui

Até o momento eu consegui pegar o id do cliente e a partir dele retornar um array com todos id das transações deste cliente.

async balance(req, res) {     const id = req.params.id      const clientTransactions = await Transaction.find({clientId: id}, '_id')       const transactionsId = clientTransactions.map((transaction) => {         return transaction._id     })      return res.json(transactionsId) } 

e tenho como retorno um array com todos estes respectivos id das transações

[   "5d20ff7bcce9e22ae36f26de",   "5d20ff86cce9e22ae36f26e1" ] 

porém, como conseguiria filtrar como numa cláusula WHERE apenas as transações com o campo statusPayable sendo ‘paid’

Nodejs functions to load and save RSA keys

I’m creating my first real life Nodejs project. I’ve created some files and all work, but I’m not satisfied about what my files look likes. It’s unreadeble.

For example, I work of a file to manage JWT sessions and RSA keys.

For this file, I need two function to load and save the RSA private key.

This Node.js style guide says to put require at the top of documents.

'use strict';  const logger = require('./logger')(module.filename); const NodeRSA = require('node-rsa'); const jwt = require('jsonwebtoken'); const fs = require('fs');  const loadKeyFromDisk = (path) => new Promise((resolve, reject) => fs.readFile(path, 'utf-8', (error, data) => {   if (error) {     reject(error);     return;   }   resolve(data); })); const saveKeyToDisk = (path, key) => new Promise((resolve, reject) => fs.writeFile(path, key, 'utf-8', (error) => {   if (error) {     reject(error);     return;   }   resolve(); }));  [...]  modules.exports = {...}; 

But, I also learn to put variables into small context as possible

'use strict';  const logger = require('./logger')(module.filename); const NodeRSA = require('node-rsa'); const jwt = require('jsonwebtoken');  const { loadKeyFromDisk, saveKeyToDisk } = (() => {   const fs = require('fs');    return {     loadKeyFromDisk: (path) => new Promise((resolve, reject) => fs.readFile(path, 'utf-8', (error, data) => {       if (error) {         reject(error);         return;       }       resolve(data);     })),     saveKeyToDisk: (path, key) => new Promise((resolve, reject) => fs.writeFile(path, key, 'utf-8', (error) => {       if (error) {         reject(error);         return;       }       resolve();     }))   }; })();  [...]  modules.exports = {...}; 

I’ve also tried some others style, but I think it’s don’t look like professionnal and clean code…

'use strict';  const logger = require('./logger')(module.filename); const NodeRSA = require('node-rsa'); const jwt = require('jsonwebtoken'); const fs = require('fs');  const loadKeyFromDisk = (path) => {   return new Promise((resolve, reject) => {     fs.readFile(path, 'utf-8', (error, data) => {       if (error) {         reject(error);         return;       }       resolve(data);     });   }); }; const saveKeyToDisk = (path, key) => {   return new Promise((resolve, reject) => {     fs.writeFile(path, key, 'utf-8', (error) => {       if (error) {         reject(error);         return;       }       resolve();     });   }); };  [...]  modules.exports = {...}; 

Did you have somes advices or idea to improve my coding style?

My complete code Here : https://pastebin.com/kXvxNd2k

How to structure multiple single page forms and handle them in nodejs

I have a html form using express-handlebars inside a loop that gets rendered a certain amount of times based off how many users there are assigned to a group. So if there are 5 users the below code between the “#Each” gets loaded 5 times.

How do I structure this so that I can Post it back to node and write it to mongoDB in terms of what I use for the id and name.

I couldn’t find anything related, if there’s anything on here please link it 🙂

<form action="/users/rsvp" method="POST">                 {{#each docs}}                 <div class="card border-secondary mb-3">                     <div class="card-header"></div>                     <div class="card-body">                         <h4 class="card-title">{{this.name}}</h4>                         <div class="form-check">                             <input class="form-check-input" type="radio" value="1" id="{{this._id}}"                                 name="{{this._id}}">                             <label class="form-check-label" for="{{this.id}}">                                 Attenting                             </label>                         </div>                         <div class="form-check">                             <input class="form-check-input" type="radio" value="0" id="{{this._id}}"                                 name="{{this._id}}">                             <label class="form-check-label" for="{{this._id}}">                                 Not Attenting                             </label>                         </div>                         <div class="form-group">                             <label for="DietaryRequirements"></label>                             <input type="text" id="DietaryRequirements" name="DietaryRequirements" class="form-control"                                 placeholder="Dietary Requirements" />                         </div>                     </div>                 </div>                 {{/each}}                  <button type="submit" class="btn btn-primary btn-block">                     RSVP                 </button>              </form> 

How to sandbox an exe using nodejs?

I’ve created an online compiler for a project which untrusted C code gets sent to the server (nodejs using express), written to a file, compiled and then the exe runs and it either sends an stderr or stdout back to the client.

I need some ideas or guidance on how to sandbox/contain this so the user cannot write malicious C code which would be executed on the server, is there a way to just sandbox the exe that has been created or will I have to sandbox the full nodejs backend app?

nodejs Jsonwebtoken express.js

Boa tarde pessoal, estou tentando realizar a autenticação de uma rota, porem nao esta dando certo,

1ª gero o token com um usuario mockado:

app.post(‘/api/login’, (req, res) => {

// Mock user const user = {   id: 1,    username: 'teste',   email: 'teste.mendes@gmail.com' }  jwt.sign({user}, 'secretkey', { expiresIn: '30s' }, (err, token) => {   res.json({     token   }); }); 

});

2º criei uma funcao verify

function verifyToken(req, res, next) {
const bearerHeader = req.headers[‘authorization’];
if(typeof bearerHeader !== ‘undefined’) { const bearer = bearerHeader.split(‘ ‘); const bearerToken = bearer[1]; req.token = bearerToken; next(); } else { // Forbidden res.sendStatus(403); } }

3ª criado a rota, app.get(‘/api/cidades’, verifyToken, (req, res) => {
jwt.verify(req.token, ‘secretkey’, (err,data) => { if(err) { res.sendStatus(403); } else { res.json({ message: ‘Post created…’, data

    });   } }); 

});

Gostaria que viesse os dados da cidade no banco de dados, e esta vindo os dados do usuario mockado:

{ “message”: “Post created…”, “req”: { “user”: { “id”: 1, “username”: “teste”, “email”: “teste.mendes@gmail.com” }, “iat”: 1561404207, “exp”: 1561404237 } }

Communication between nodejs and python

I want a non-class method to be executed whenever the static class method is called. This static class method will be called from some other program present in some other directory, every 10 seconds. The non-class method will call the python script by spawning.

I have done this by calling a non-class method from a static class method. I want to know whether the way I am doing this is right or not. Or Is there some other good way.

home/sampath/file1/program1.js

class A {  constructor (name, age) {   this.name = name;   this.age = age;  }   static updateDate (name, age) {   let obj = new A (name, age);   callFunc (obj);  } }  function callFunc (obj) {  //calls python script with the given object as agrument;  //argument obj.name, obj.age }  module.exports = A; 

home/sampath/file2/program2.js

const A = require ('../file1/program1');  //This statement is executed every 10 seconds. A.updateData ('some_name', 'some_age'); 

Is the good coding practice I have done, or some better way is there?

What should I use to encrypt data between a centralized server and multiple devices running NodeJS?

I have a centralized server and DB that each of my devices polls every ten seconds. The centralized server may respond with a list of “active jobs”, which the devices will then run.

I need to ensure the data sent from the server to the devices is encrypted and only each device can decrypt that.

I was thinking I would need to generate a key pair on each device at installation and send the public key to be stored on the centralized server. The server then encrypts data out using the public key, and each device decrypts that data once ingested using the private key.

Does this make sense? Which encryption scheme should I be using? My server is running Laravel (PHP) and as mentioned each device is running a NodeJS daemon.

Instancia do axios não retorna no export do nodejs

Estou tentando retornar a instancia criada através do axios pelo module.exports, porém quando tento usa-lá me da esse erro:

http(…).get is not a function

Meu arquivo http-common.js

var axios = require('axios');  var instancia = axios.create({     baseURL: `http://jsonplaceholder.typicode.com/`, });  module.exports = instancia; 

Meu index.js

var http = require('./app/infraestrutura/http-common')(); http.get('/users')         .then(function(response){             console.log(response)         }).         catch(function(err){             console.log(response)         })