How to organise routes for an app with subcategories in Node.js and make them modular

I have a basic grasp on Node.js and I’m playing with making my own app. While I understand how routes and controllers work, I only see tutorials where all the routes have similar structure which is very simplified and rigid.

I have three requirements for my app:

  1. To be able to display categories/subcategories without having to use IDs which are almost exclusively used in tutorials. The URL I would like is as follows:www.domain.com/women/dresses/silk/dress-item-1

  2. It has to be modular so that I can add new categories and not have to define routes for all categories. For example, if I added ‘shirts’, I would automatically have www.domain.com/women/shirts/... available. Or if I added ‘men’, I would have www.domain.com/men/... available.

  3. I would like to have the option of adding and stacking subcategories indefinitely in some way to get something like www.domain.com/women/dresses/silk/long/short/dress-item-1. I know I can use tags to define items, but I am wondering if this is possible instead.

NODE.JS Dentro de llamado get de un REST la sentencia sigue sin esperar que finalice un for

Tengo el siguiente problema: Cuando ejecuto la sentencia SQL y logro cargar el array, me muestra el primer console.log con el mensaje “Pase primer select”, luego pasa por un for donde tiene otra subquery que terminaría de cargar el array, el tema es que lo pasa por alto y me muestra el console.log con el array final, pero, luego me muestra el resultado de la subquery, es como que no esperara al for para finalizar, tienen idea de como lo podría solventar al tema? me vendría de muchísima ayuda. desde ya muchas gracias y Saludos.

Codigo:

app.get('/productos/ConfigPF', function(req, res) {     //res.json('get Usuarios')     let tipProd = req.query.tip_prod || 0;     tipProd = Number(tipProd);      let idProd = req.query.id_prod || 0;     idProd = Number(idProd);      let arrayprod = {} // empty Object     let key = 'ConfiracionPF';     // empty Array, which you can push() values into     arrayprod[key] = [];      queryDB(`SELECT CA.ETIQUETA, CA.NOM_FORMU , CA.ID_CAMPO,CA.TIP_CARGA,ID_CATG,ID_CAM_STOCK from tb_config_campo_pf PF,tb_config_campo CA  where pf.tip_prod = $  {tipProd} and pf.id_pf = $  {idProd} and pf.tip_prod = ca.tip_prod and pf.id_campo = ca.id_campo`)          .then(         // success         (rs) => {             // realizas operaciones con rs y llenas el array             rs.forEach(function(row) {                 //console.log(row.IMAGEN);                 //Armar JSON                 var imagenf = ab2str(row.IMAGEN);                  var data = {                     etiqueta: ab2str(row.ETIQUETA),                     valor_col: ab2str(row.NOM_FORMU),                     id_campo: row.ID_CAMPO,                     valor: 0,                     tip_carga: row.TIP_CARGA,                     valor_combo: "0",                     id_categ: row.ID_CATG,                     id_cam_stock: row.ID_CAM_STOCK                 };                 arrayprod[key].push(data);             });             disconnectFromDB();             console.log("Pase primer Select"); // verificas que tienes los datos              let sqlsentencia = "";             // realizas operaciones con tu array             for (let i in arrayprod) {                 for (let j in arrayprod[i]) {                     if (arrayprod[i][j].tip_carga == 1) {                         if (arrayprod[i][j].id_cam_stock == 5)                         {                             sqlsentencia = `select CAMPO5 AS CAMPO from TB_ITEM_STOCK where id_categoria =  $  {arrayprod[i][j].id_categ}`;                         }                          if (arrayprod[i][j].id_cam_stock == 6)                         {                             sqlsentencia = `select CAMPO6 AS CAMPO from TB_ITEM_STOCK where id_categoria =  $  {arrayprod[i][j].id_categ}`;                         }                          if (arrayprod[i][j].id_cam_stock == 7)                         {                             sqlsentencia = `select CAMPO7 AS CAMPO from TB_ITEM_STOCK where id_categoria =  $  {arrayprod[i][j].id_categ}`;                         }                          if (arrayprod[i][j].id_cam_stock == 8)                         {                             sqlsentencia = `select CAMPO8 AS CAMPO from TB_ITEM_STOCK where id_categoria =  $  {arrayprod[i][j].id_categ}`;                         }                          if (arrayprod[i][j].id_cam_stock == 9)                         {                             sqlsentencia = `select CAMPO9 AS CAMPO from TB_ITEM_STOCK where id_categoria =  $  {arrayprod[i][j].id_categ}`;                         }                          if (arrayprod[i][j].id_cam_stock == 10)                         {                             sqlsentencia = `select CAMPO10 AS CAMPO from TB_ITEM_STOCK where id_categoria =  $  {arrayprod[i][j].id_categ}`;                         }                          queryDB(sqlsentencia)                         .then((rs) =>   {                             // realizas operaciones con rs y llenas el array                             console.log("Pase segundo Select");                             let valores = "";                             rs.forEach(function(row) {                                 if (valores = "")                                 {                                     valores = ab2str(row.CAMPO);                                 }                                 else                                 {                                     valores = valores + "_";                                     valores = valores + ab2str(row.CAMPO);                                 }                              });                             arrayprod[i][j].valor_combo = valores;                             valores = "";                             disconnectFromDB();                                                  },                          (err) => {                             console.log("error");                         }); // termina el then()                     }                 }             }              console.log(arrayprod);            // ahora ya puedes hacer uso de res.json            res.json({                ok: true,                arrayprod            });         },         (err) => {             console.log("error");         }); // termina el then() }); // termina el app.get() 

http.get in node.js return undefined

Hi I’ve made a function to make api request and it works fine (when I put console.log where I return a data it perfectly logs what should be there but I can’t make it to write data to variable where I call this function.

Can it be that requestWheather() function finishes before request is done?

How can I fore it to wait until request() function finish?

Here is my code:

const http = require('http')  const accu = {     domain: 'http://dataservice.accuweather.com/',     apiKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',     locationKey: 'XXXXX',     languageCode: 'pl-pl' }  requestWheather()  function requestWheather() {     let location = request(`locations/v1/$  {accu.locationKey}?apikey=$  {accu.apiKey}&language=$  {accu.languageCode}`)     let currentConditions = request(`currentconditions/v1/$  {accu.locationKey}?apikey=$  {accu.apiKey}&language=$  {accu.languageCode}&details=true`)     console.log(location) }  function request(url) {     let requestUrl = accu.domain + url      http.get(requestUrl, (resp) => {          let data = ''          resp.on('data', (chunk) => {           data += chunk         })          resp.on('end', () => {             return JSON.parse(data)         })      }).on("error", (err) => {         console.log(err.message)     })  } 

Node.js http retry do while mechanism

Hello i have implemented a simple do/while loop to handle a http request to a third-party. I don’t know when the data i receive will have elements in its array so i retry up to 10 times until the array given to me has data which then i stop and store the data in my database.

My question is in terms of performance is my API going to be affected by having this retry mechanism using a simple do/while loop? If so what is a better way to implement a retry mechanism like this??

public MAX_RETRY = 10;  public async processMetrics(sessionId: any, side: any): Promise <any> {    try {      let metrics;     let retryAttempts = 0;      do {       await new Promise((done) => setTimeout(done, 2000));       metrics = await this.getMetrics(session._id, sessionRequest._id);       retryAttempts++;      } while (!metrics.body.metrics.length && (retryAttempts < this.MAX_RETRY));      // Store in DB   } catch (err) {     }  }  public async getMetrics(sessionId: any, requestId: any): Promise <any> {    const url = this.config.backendUrl + "/check/metrics";    const options = {     uri: url,     headers: {       "X-IDCHECK-SESSION_ID": sessionId,     },     body: {},     json: true,     resolveWithFullResponse: true,   };    const metrics = await request.get(options);    return metrics;  } 

btw i am calling processMetrics from a different async function.

processMetrics is calling a backend (getMetrics) every 2 seconds, it will retry 10 times to see if the result is ready. If it is i will store something in the database and then return.

Is this method of hashing passwords good? Node.js

I am currently developing a login for my website, (Using node.js and MySQL) and would like some feedback on the password hashing code.

const crypto = require('crypto');  function RandomSaltString(length) {      return crypto.randomBytes(Math.ceil(length/2))//I have absolutely no idea what this is         .toString('hex')        //And this         .slice(0,length);      //Well I think know this thought  };  function Hash(password, salt) {     var hash = crypto.createHmac('sha512', salt);     hash.update(password);      return hash.digest('hex'); };  function preparePasswordForStorage(password) {      var salt = randomString(20);     const hashedPassword = hashFunc(password, salt);      //Will encrypt the hashed password and salt here once I figure it out.      return {         hashedPass: hashedPassword,         salt: salt      //Will be stored in db directly after this.     } }; 

I know this isnt exactly a node.js sub, but well yeah. Thanks in advance guys!

JavaScript | node.js | Помогите разобраться с Массивом

Такая проблема, у меня есть 2 массива, к примеру эти:

let product = ["val_a", "val_b", "val_c", "val_d"]; let price = ["val_0", "val_1", "val_2", "val_3"]; 

Мне нужно сделать так, чтобы значение val_a принадлежало значению var_0 (var_b -> var_1 etc), т.е. чтобы, когда я вынимал переменные val_a и var_0, они шли в формате: val_a, val_0, дабы ими можно было спокойно эксплуатировать.

пример как я себе это (эксплуатирование) представляю:

let product = ["val_a", "val_b", "val_c", "val_d"]; let price = ["val_0", "val_1", "val_2", "val_3"]; let product_price = ["val_a", "val_0"] alert('Товар: $  {product_price[0]}\nЦена: $  {product_price[1]}') 

Performance comparison of Legacy VB6 Software vs Node.js and React.js

my company just started a new production management software by using serial communication to scales. My company has already developed the software using VB6 in 2006 and keep using that outdated system until now.

The new software will be a centralized management software using local server, and planned to use Node.js (Express) and React for frontend. As for the serial communication, the scale will be connected to a subserver in each client and connected to the client’s browser via socket.io

So i want to ask, how fast the Node + Express + React + Socket io compared to VB6? Just imagine if all the node, express etc is running on the same computer. Or is there any article/data that compare both technology?

Or perhaps i should do the test and benchmark myself? But considering both technology as so different, what parameters that i should compare? I really need an expert opinion

Thanks in advance

Combining await and Promise.all not working in my node.js microservice

I have a pretty complicated node.js microservice that utilizes graphql as well, to first query a database, then populate an array with the returning values, and then run a graphql mutation inside an await and Promise.all call. With the following code I keep getting an error: ‘await has to be used inside an async function’ – but, I already have everything wrapped inside an asyn function! Can someone point out what I’m doing wrong? (PS: there might be other errors as well that I’m not seeing because I can’t get past the first error)

  const QryAllBooks = {     type: new GraphQLList(BookType),     args: {},     async resolve(){           return new Promise((resolve, reject) => {              let sql = singleLineString`                   select distinct t.bookid,t.bookname,t.country                   from books_tbl t                   where t.ship_status = 'Not Shipped'               `;              pool.query(sql, (err, results) => {                if(err){                   reject(err);                }                resolve(results);              const str = JSON.stringify(results);             const json = JSON.parse(str);              const promises = [];             for (let p = 0; p < results.length; p++){                const book_id = json[p].bookid;                const query = `mutation updateShipping                               {updateShipping                                (id: $  {book_id}, input:{                                   status: "Shipped"                                })                                { bookid                                  bookname }}`                 promises.push( query );            }            //I need an await function so that apolloFetch             //goes in sequence of bookid, one after the other           await Promise.all(Object.values(input).map(async (promises, i) => {                   apolloFetch({ promises[i]});                   })                  .catch(( e ) => {                      errorLogger( 29, 'Error', e );                  )};                   });             });         }       };       module.exports = {           QryAllBooks,           BookType      }; 

Problema con impresora en Node.js

Estoy intentando lanzar contra una impresora un txt con la intención de que se imprima directamente.

Uso la librería node-printer y aunque no me da ningún error, el documento se me queda en la bandeja de salida indefinidamente y no llega realmente a la impresora.

Estoy haciendo las pruebas con Windows 10 (que va a ser el entorno de producción).

var printer = require("printer");     filename = process.argv[2] || __filename;  console.log('platform:', process.platform); console.log('default printer name: ' + (printer.getDefaultPrinterName() || 'is not defined on your computer')); console.log('try to print file: ' + filename);  if( process.platform != 'win32') {     printer.printFile({filename:filename,     printer: printer.getDefaultPrinterName(),      success:function(jobID){        console.log("sent to printer with ID: "+jobID);     },     error:function(err){        console.log(err);     } });  } else {   var fs = require('fs');   printer.printDirect({     data:fs.readFileSync(filename).toString(),     printer: printer.getDefaultPrinterName(),      type: 'RAW',     success:function(jobID){       console.log("sent to printer with ID: "+jobID);     },     error:function(err){       console.log(err);     } }); 

Hay una versión de esta misma pregunta aquí.