Using node, is it possible to wait for a database entry to appear?

Is it possible with node to asynchronously wait for a record to appear in a database table?

I use a SMS service where I send a POST request to an API endpoint where I receive a sms-id (uuid) then a “Delivery Report” as XML sent to an API-endpoint on my server; eg. sms.mydomain.com.

This sms-id is used to match a reportId field in the “Delivery Report”. This Delivery Report can take anywhere from 1 to 60 seconds to be sent/received by my endpoint, parsed and inserted into a DB table.

So far, I’ve used a simple timeout script to check if a record with a reportId that matches the sms-id has been inserted into a table. This script has been edited a bit to clearly display my use-case and setup.

const axios = require('axios');  const setAsyncTimeout = (cb, timeout = 0) => new Promise(resolve => {     setTimeout(() => {         cb();         resolve();     }, timeout); });  const url = 'https://api.mydomain.com/v1/get/7654fec9-33ba-4881-931d-0e6f4d7de710'; const getData = async url => {     try {         const response = await axios.get(url);         const data = response.data;         await setAsyncTimeout(() => {             // Do whatever with the returned Delivery Report here         }, 30000);     } catch (error) {         // Add entry to monolog. Endpoint returns json or 404/500         $  log->error(`Could not find a Delivery Report with this ID.\n$  {error}`);     } };  getData(url); 

With the code above, if a Delivery Report is found where the given SMS-id and reportId matches, it returns the table as JSON for further handling, if no matching Delivery report is found, a 404 HTTP error message is returned instead.

While this method certainly works, it misses checks for about 15-20% of reports that take longer than 30 seconds to be received by my endpoint. I don’t feel it’s very clean or right to do it like this. I believe there has to be a better approach but looking up the issue has yielded few results.

Node – req.body has values but returns undefined

So in Node/Express, I can see the body value using body-parser and console.log(req) returns JSON with the body value:

 body: { email: [Object], cname: '', pass1: '', pass2: '' }, 

But req.body always returns undefined. I know the positioning is important, and I’ve seen a lot of threads on it, but I have my routes in separate files, so I think this is causing some issue.

Here’s the app.js code:

//(1) Server Config const express = require('express') const app = express() const port = 3000 app.set('view engine', 'pug') const path = require('path') app.use('/', express.static(path.join(__dirname, '/')))  //(2) Modules const bodyParser = require('body-parser') app.use(bodyParser.json()) app.use(bodyParser.urlencoded({extended: true}))  //(3) Routes app.use(require('./routes/account_create')) app.use(require('./routes/account_register'))  //(4) Server Start app.listen(port, () => console.log(`Listening on $  {port}`)) mongoose.connect(`mongodb://$  {db_server}/$  {db_name}`)     .then(() => console.log('Connected to DB'))     .catch(err => console.log(err)) 

The form is filled out on account_create route, then the POST is on account_register.

Here is account_register:

const express = require('express') const router = express.Router()  router.post('/account_register', (res, req) => {     console.log(req.body) //returns undefined })  module.exports = router 

Just in case it is needed, here is the code for the account_create route and PUG:

const express = require('express') const router = express.Router()  router.get('/account_create', (req, res) => {     res.render('account_create') })  module.exports = router  html     head         h1 Create Account         form(action='/account_register' method='POST')             .form-group                 label(for='email') E-Mail                 input#email(type='email', name='email')             .form-group                 label(for='cname') Character Name                 input#cname(type='text', name='cname')             .form-group                 label(for='pass1') Password                 input#pass1(type='password', name='pass1')                 label(for='pass2') Password Confirmation                 input#pass2(type='password', name='pass2')             button.btn(type='submit') Register         script(src='../scripts/account_create.js') 

In what situations / with what nodes should a node ping / not ping?

I was recently looking at a network in which the client-machines that accessed a webservice endpoint, but which could not ping the webservice endpoint.

And there are other machines that can ping the webservice endpoint, but which do not utilize it.

However, the other machines do connect to service the client-machines, and of course can ping both.

All machines in question are on a private network, that extends to private and public physical locations.

So, why would some of these machines DROP packets and others ACCEPT them?

How do I print Node pointers so that I can debug in C++? [on hold]

I’m trying to solve this problem and I would like to know how to output the values inside of the *Node object so that I can debug it. I don’t really know much about C++. I come from a JavaScript background and would like to know more about how JS works under the hood so I’m studying CS concepts.

https://www.hackerrank.com/challenges/binary-search-tree-lowest-common-ancestor/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=trees&h_r=next-challenge&h_v=zen

I tried this…

    Node *lca(Node *root, int v1,int v2) {         cout << *root->data;         cout << v1;         cout << v2;         return 0;     } 

but I keep getting seg fault errors (and I have no idea what that means.)

Could someone explain in excruciating detail what I’m doing wrong?

How to avoid duplicate vertex node on AgensGraph?

I want to create edge on two vertexes.

agens=# create (:v1{id:1}), (:v1{id:2}); GRAPH WRITE (INSERT VERTEX 2, INSERT EDGE 0) agens=# create (:v1{id:1})-[:e1{id:3}]->(:v1{id:2}); GRAPH WRITE (INSERT VERTEX 2, INSERT EDGE 1) agens=# match (n:v1) return n;         n          ------------------  v1[3.1]{"id": 1}  v1[3.2]{"id": 2}  v1[3.3]{"id": 1}  v1[3.4]{"id": 2} (4 rows) 

But, There is duplicated vertex on it.

How to avoid duplicate vertex node on AgensGraph?

Node program runs in Terminal, but not as a service or on command “do shell script” from AppleScript

I have a call (mercury-parser via Yarn) that converts Web pages to lines of structured text. It runs in node on 3.5 GHz, 6-Core Mac Pro (MacPro6,1) with 16GB RAM and D700 GPUs, running macOS 10.14.5 very well, but I’m struggling to run it as a service / on demand without opening terminal app and typing.

I would much prefer it to run within an AppleScript. Here is the line of code:

/Users/me/.yarn/bin/mercury-parser https://postlight.com/trackchanges/mercury-goes-open-source 

If I run it in Terminal (using either /bin/bash or /bin/sh), I get the proper result: fourteen lines of structured text from the Web page.

If I run it in a shell script, starting with either “#!/bin/sh” or “#!/bin/bash”, I get: env: node: No such file or directory If I run it in Script Editor as: do shell script “/Users/me/.yarn/bin/mercury-parser https://postlight.com/trackchanges/mercury-goes-open-source” I get: env: node: No such file or directory

Here are both my .profile and my .bash_profile texts:

export PATH="/usr/local/bin:/usr/local/sbin:/usr/local/mysql/bin:$  PATH"  export PATH="$  HOME/.yarn/bin:$  HOME/.config/yarn/global/node_modules/.bin:$  PATH"  [[ -s $  HOME/.nvm/nvm.sh ]] && . $  HOME/.nvm/nvm.sh  # This loads NVM  source ~/.nvm/nvm.sh  export NVM_DIR="$  HOME/.nvm" [ -s "$  NVM_DIR/nvm.sh" ] && . "$  NVM_DIR/nvm.sh" # This loads nvm 

What do I have to do to get the code to run outside of Terminal?

Видеоуроки написания простого интернет-магазина на Node js на www.youtube.com? Или код какого-то интернет магазина с GitHub c коментариями?

Искал видеоуроки по написанию сайта на node js, с толкового нашел только видеоуроки Алексея Лущенко:
https://www.youtube.com/playlist?list=PLM7wFzahDYn…
Но там он изложил только некоторые видео со своего курса, чтобы получить другие надо оплатить деньги, что на данный момент из-за моего финансового положения сложно.
Посоветуйте какие-то видеоуроки где:
1) Видеоурок отображает весь процес написания интернет-магазина от начала вплоть до того момента когда он готов к залитию на хостинг
2) Желательно кончено на русском но если знаете какой-то видеурок на английском, который по качеству лучше существующих в сети русскоязычных уроков, и автор четко и понятно объясняет то пойдет и на английском языке, готов несколько часов лишних потратить на перевод
3)Минимум компонентов на сайте, достаточно самое главное:
-регистрация и вход на сайт пользователя
-работа з с базой данных
-работа с товарами (фильтрация товаров, добавления товаров в корзину, или в список желаний, оплата товаров)

Или сбросьте ссылку кода с GitHub какого-то интернет-магазина на Node.js c коментариями к каждой строчке кода(в идеале) или хотя бы до каждой функции/компоненте кода, что б понять что она делает на сайте.

Finding rank of newly inserted node in AVL tree augmented with rank of node

My prof was talking about how to augment a tree to efficiently find the key with a given rank. On the way to getting the right answer (store the size of the subtree rooted at each node), he proposed augmenting each node with it’s rank. That way finding the node with a certain rank is a simple binary search. But he said this wouldn’t work because insertion would be $ \Theta(n)$ . I understand that this is because in the worst case the newly inserted node has rank 0 and so the rank of each node in the tree must be incremented by 1. What I am interested in knowing is an algorithm for computing the rank of a newly inserted node. At first I thought that if a node $ n$ is inserted to the left of a leaf $ l$ with rank $ k$ then the rank of $ n$ is $ k-1$ , or $ k+1$ if inserted right of $ l$ . I found a counter example to that so I know it is not the case. So how would this be done?

Tensorflow js loadLayersModel range error on node 8.10/aws lambda “byte length of Float32Array should be a multiple of 4”, works on browser?

I have trained and saved an image classification CNN using tensorflow js following the browser example provided.

https://codelabs.developers.google.com/codelabs/tfjs-training-classfication/index.html#6

Then I uploaded my model’s json and bin file to a public s3 bucket, and tried to load it like so in a lambda so that it can later on make and return a prediction when I call model.predict().

var tf = require('@tensorflow/tfjs'); global.fetch = require('node-fetch');  exports.handler = async function(event, context) {     var data = typeof event === String ? JSON.parse(event) : event;      var shidDataItem = data.shipDataItem;     var image = predictionData.tripImage;      console.log('getting model');     const model = await tf.loadLayersModel('https://s3.amazonaws.com/{my_bucket}/my-model.json');     console.log(model); } 

But when I test this I get the following error –

{   "errorMessage": "byte length of Float32Array should be a multiple of 4",   "errorType": "RangeError",   "stackTrace": [     "typedArrayConstructByArrayBuffer (<anonymous>)",     "new Float32Array (native)",     "_loop_1 (/var/task/node_modules/@tensorflow/tfjs-core/dist/io/io_utils.js:159:30)",     "Object.decodeWeights (/var/task/node_modules/@tensorflow/tfjs-core/dist/io/io_utils.js:189:9)",     "/var/task/node_modules/@tensorflow/tfjs-layers/dist/models.js:298:50",     "step (/var/task/node_modules/@tensorflow/tfjs-layers/dist/models.js:54:23)",     "Object.next (/var/task/node_modules/@tensorflow/tfjs-layers/dist/models.js:35:53)",     "fulfilled (/var/task/node_modules/@tensorflow/tfjs-layers/dist/models.js:26:58)",     "<anonymous>",     "process._tickDomainCallback (internal/process/next_tick.js:228:7)"   ] } 

However, this snippet works on the browser –

const model = await tf.loadLayersModel('https://s3.amazonaws.com/{my_bucket}/my-model.json'); 

Has anyone encountered this issue? Any suggestions for loading a model in a lambda to make a quick prediction? Thanks for your time.