Tuesday 30 June 2020

How I started a globally trending COVID tracking API in node.js during quarantine!

https://elitedamyth.xyz/2020-06-30-How-I-started-disease-sh/

Submitted July 01, 2020 at 06:00AM by EliteDaMyth

Learning Node is super easy?

Recently I started learning Backend, and well Node ofc. So I searched internet and came across these websites and tutorials on YouTube which teaches NodeJs in like 3 hours (with 1.5x playback speed). Starts with what NodeJs is, websites/companies using it, problems of multi-threading and single threading in Node as a solution, node is event driven, asynchronous (mere statements and little to no explanation). And then the practical parts i.e installing, what is npm, JSON, importing modules - fs, http, eventEmitter, body-parser express (just to create a server and address get/post request). Few videos also talked about cors and middleware etc. So is this all that I need to know in Node other than connecting and using databases? Or is there more? Please guide me.

Submitted July 01, 2020 at 06:26AM by Vizibile

Node v14.5.0 (Current)

https://nodejs.org/en/blog/release/v14.5.0/

Submitted July 01, 2020 at 02:19AM by dwaxe

Huge oversight

A few days ago i had commented on a post asking about aync/await vs. promises. I admit the argument got a little heavy but anyway the point I was arguing about await being blocking missed a tiny detail I forgot to mention that you would have to wrap your scope in (async ( )=>{ })(). I never implied that it would be blocking your main thread, but it would how ever block the scope of the (req, res)=>{ } callback, because the entire callback would be async since there is no other body except the async lambda. Then if you were to call console.log('1'); await doSomethingAsync(); // for(...i < 100...){}console.log('2') Console.log('3') you would get 1 2 3 instead of 1 3 2. Tiny detail I missed way after the fact, but ehh.

Submitted July 01, 2020 at 12:01AM by IroncladFool597

Node v12.18.2 (LTS)

https://nodejs.org/en/blog/release/v12.18.2/

Submitted July 01, 2020 at 12:19AM by dwaxe

DDB-Table v1.0: Safe TypeScript schemas for DynamoDB

https://github.com/neuledge/ddb-table

Submitted June 30, 2020 at 10:21PM by moshestv

puppeteer/NodeMailer Help

Hi, i'm trying to install an html page and save it as a pdf with puppeteer.The thing is lets say i'm trying to save articles from a website, how can i save specific ones through categories, i mean finance for example how can i enter the finance section and then go over the last ones and have them installed?or get the links for them if i know that the div's are contain href of the article itself.Thanks a lot!!

Submitted June 30, 2020 at 09:55PM by Eli3221

If interested - TomTom Devs is live on Twitch discussing everything from Geofencing to asset tracking to even Roswell Aliens!

https://www.twitch.tv/tomtomdevs

Submitted June 30, 2020 at 08:12PM by TomTom_developers

Tips for a beginner?

Basically the heading. I'm starting out learning node and I'm not sure what resources I should be using and what my strategy should be to get really gud at node. Any advice will be much appreciated

Submitted June 30, 2020 at 08:04PM by spacespiceboi

Best way to forecast time series data?

I have arrays of time series employment data that I'd like to create estimates for future growth on. I've been looking for a good npm module that does something like a boosting algorithm or at minimum a good regression but have been disappointed w overly complex packages. Anyone have any good ideas where simple date, count tuples can project out one or two periods based on window of X periods back?

Submitted June 30, 2020 at 07:31PM by bobbysteel

calculate age by dob (dd/mm/yyyy)

i get dob asbody.dob --> dd/mm/yyyyi run code as -} this method gives output in mm/dd/yyyy, but i want in dd/mm/yyyy

Submitted June 30, 2020 at 06:53PM by Manisha_987

Angular, JavaScript, CSS, Html, NodeJS quick Notes...

https://www.tutorialslogic.com/node-js?ver.lat.tr

Submitted June 30, 2020 at 06:56PM by raginimishra

hapijs/joi will be deprecated 😟 - here's a tutorial on how to use yup (a joi alternative) for request body validation

https://www.youtube.com/watch?v=GfHsb6zPugo

Submitted June 30, 2020 at 05:18PM by prodcoder

Nodemailer module missing

Hi!So, I'm trying to write a js script that sends an email. To do this I need the nodemailer module. I am using a bin version of node to run it. I'm not sure how to npm nodemailer into it, if I can at all and where to execute npm if I can.Thanks.

Submitted June 30, 2020 at 02:44PM by CallousedFlame

Question about Twitter status codes

hi there!some time ago I made a little script that once a day checks when a username/handle is available and it worked perfectly. Today I wanted to test a few things and found out it gives me the same status code 200 (for existing and non existing users) which it didn't before. I think this has something to do with the recent changes in their website, because even the hmtl is different from before. Can someone explain what happen and how can i fix my code?BTW I use request to get the status code

Submitted June 30, 2020 at 02:23PM by sh3zza

I am having error in this node code written in typescript . Please help

https://drive.google.com/drive/folders/1_rU6BNB0FU193s9EGlCOoxs9BxxpmQ3k?usp=sharingThis is my code

Submitted June 30, 2020 at 01:13PM by simplyfatal77

A CRM template

Hi all,can anyone here can recommand me a good open source crm system?A development I would be able to install via npm or whatever way and customize it for my needs?Thanks alot

Submitted June 30, 2020 at 12:42PM by bunyyyyyyyyyu

Is this authentication flow in socket.io secure?

So I have react web app that I recently decided to add sockets to (for extra functionality) and there are some cases where only authenticated users should see certain data being emitted by the server, and also some info should only be accepted by the server (via sockets) only from authenticated users, so I built the following authentication flow and I was wondering if anyone can see any security issue with it, meaning will unauthenticated users be able to see data and emit data to and from the server or is it safe enough?This is the flow:- The user login on the frontend as usual with no socket connection what so ever, and after login in they get a login token that's stored in a cookie and used for every request they make to the server to authenticate their API calls to the backend- Once a user connects to the socket, the server in the "connection" listener takes the login token from the cookie and authenticate the user- If couldn't authenticate the user then the server emits the reason to the frontend and disconnect the socket- Otherwise if managed to authenticate the user then the server adds the user to a specific room only for that user (so if the same user logs in from multiple PCs or mobile apps all their instances will be able to receive and emit data) the rooms ID structure is "room-" and then the user ID​Here's a snippet of the code: //creating socketio instance with the server's instace const io = socketio(server) //listening for new connections io.on("connection", async (socket) => { //authenticating newly connected sockets with their login token const didAuth = await authenticate(socket) //emitting the response to the client io.to(socket.id).emit("auth", didAuth) //if couldn't authenticate then disconnecting the socket if(didAuth.error) return socket.disconnect() //adding the user to their room - "userId" is added to the socket object in the authentication function once the user successfully logs in socket.join(`room-${socket.userId}`) //adding listeners for clients emits socket.on("alert-from-client", () => { //doing stuff here that only authenticated users can do }) }) //when the server needs to emit info to the clients this function is called module.exports.emitSomething = (userId, data) => { //emitting some data only authenticated users should see io.sockets.in(`room-${userId}`).emit(data) } //authenticating the socket based on the login token of the user const authenticate = async (socket) => { let didAuth = { error: true, message: "Unknown error" }; //getting the user's login token (which was generated and saved in a cookie when they logged in on the frontend) let token = getCookie(socket.request.headers.cookie, env.LOGIN_COOKIE_ID) /* ... doing authentication stuff here with the token and setting in the above "didAuth" if there was auth error and potential error message ... */ return didAuth; }

Submitted June 30, 2020 at 10:19AM by s_trader

Headless, on-premise, multi-tenant, eCommerce solution that uses Node.js

Hi guys,Was wondering if you knew a headless, on-premise, multi-tenant, eCommerce solution, that would be not necessarily free, but installable on premise with an upfront cost and not a per-month or per-sale pricing, AND if it were in Node.js that would be a great plus, but I am asking for a lot here.All the solutions I found are hosted, over-expensive, subscription based, commission based or owned by Adobe. So I am looking for some more inspiration before I develop my own system.

Submitted June 30, 2020 at 09:33AM by UnrelatedConnexion

EnvOne - Relief from messing with your nodejs env variables across multiple environments.

It is a zero-dependency module that loads dynamic environment configurations from a ".env.config" file, and process it as environment variables into "process.env" - https://github.com/APISquare/envoneIntroduction of EnvOne (.env.config) to your nodejs eco-system

Submitted June 30, 2020 at 08:59AM by suthagar23-dev

Worrying about the npm ecosystem

https://sambleckley.com/writing/npm.htmlNot my article; just saw it on Rust subreddit.I have been really upset when I started on nodejs time ago and it's one of my main motivations to "hate" node. The dependency tree is horrible, and from my point of view it needs fixing.What do you think about this?

Submitted June 30, 2020 at 09:23AM by deavidsedice

Deploying Your NodeJS Code to a Server Every Time You Push with Github Actions

https://blog.soshace.com/deploying-your-nodejs-code-to-a-server-every-time-you-push-with-github-actions/

Submitted June 30, 2020 at 08:10AM by branikita

Next.js SSG - 3rd party css namespacing (first blog post)

https://codenal.dev/css-namespaces

Submitted June 30, 2020 at 08:25AM by gzimhelshani

node_modules cleanup

Created a simple node command line interface mo-clean to clean the unused nodule_modules from the node/angular/react or from any npm base application.npm registry link: https://www.npmjs.com/package/mo-cleangithub: https://github.com/uttesh/mo

Submitted June 30, 2020 at 07:56AM by avis_learn

Monday 29 June 2020

Heaviest objects in the universe

https://i.redd.it/3xe8hfrqaz751.jpg

Submitted June 30, 2020 at 05:53AM by wise_introvert

Desktop Appication That Starts Local Node Server

Hi! I've recently seen more software packages like the newest version of PgAdmin 4, which opens in the browser instead of a standalone app:https://vimeo.com/433850138I'm wondering how these people do this; I'm confused about the whole system that makes this happen. If I wanted to do the same thing a Node application, having built a local offline desktop tool whose interface is made with Node/React, how would I publish a similar tool where the user opens the application like any other apps except it opens a local web server?With my limited knowledge, this is weirdly reminiscent of a Docker container. This is because, while the package is not small, once installed it can run in a vast variety of environments. It's not like PgAdmin 4 requires a specific set of system packages to be installed in the environment (which is what something like "node index.js" would require). And I feel like this is a pretty powerful way to deploy offline bespoke software tools for people like me, whose only experience is on web application development.I'm sorry if this is not entirely related to Node; I'm posting here because, if I were to make such a thing, I would do it with Node since that's mainly all I've used and I'd like to know specific details to make it happen.Thank you!

Submitted June 30, 2020 at 04:43AM by chankeam

Advice for adding authentication/authorization to a Node.js App

Hi everyone. I have a few questions regarding authentication/authorization for a small express API that I have running on Google Cloud Platform (GCP). Please forgive my ignorance, I'm not terribly experienced with Javascript or API development.Here's the gist of what I have:MySQL database on GCPNode.js express app on GCP with 4 endpoints, all of which retrieve information from the DBA React.js front end that makes calls to the Node.js AppA React Native mobile appMy main issue right now is that my Rest API is exposed and anyone can make requests to it. While there isn't any inherently sensitive info in the responses, it's obviously not ideal to have unwanted requests hitting your API. I was thinking the best thing to do would be to implement an API key system so that only requests with a valid key get served. So my questions are:What sort of authentication/authorization system would you recommend that I implement? (And if possible, link some documentation or a tutorial)How can I securely ensure that my front ends have valid keys? The Reactjs app will probably just be on a GCP instance as well, but the React Native app will be distributed through the google play store. How do I ensure that each app distribution gets a unique key? Does each app need a unique key?

Submitted June 29, 2020 at 11:53PM by smutje-mansur

Question about compiling to .exe with auto update functionality

Hello! I want to create a command line node app that can automatically update itself by checking its own version with the latest GitHub release version. I also want my app to be packaged as a .exe for windows so users don't need node and npm installed. I understand how to package my app as a .exe file, but I am unsure how to add auto update functionality. I would greatly appreciate any help!

Submitted June 29, 2020 at 11:15PM by SuicidalKittenz

Im creating a npm package, should I use es6 modules or commonjs?

npm: https://www.npmjs.com/package/eventmongerHi,I've had this bit off code I kick around from project to project for emitting events and I figured now that I have time on my hand that I should make it into a real package!The main difference between this and other systems is that you pass the actual event around instead of using a string, that way a linter can help you out and you cant misspell events.That also lets it be faster since there is no indexing events. I did some benchmarking and it seems like its faster than EventEmiter3.I was wounding if people had any tips on how to speed it up more or any other feedback. I'm currently using es6 modules and was wondering if that's considered okay or if I should use commonjs.Thanks in advance!

Submitted June 29, 2020 at 10:10PM by FelixMo42

AWS S3 SignedUrl upload is corrupting images (JPEG, PNG) but PDFs are fine?

A Complete Guide to Data Modeling Concepts

https://codezup.com/data-modeling-concepts-mongodb-tutorial/

Submitted June 29, 2020 at 08:17PM by CodezUp

NodeJS quick overview...

https://www.tutorialslogic.com/node-js?ver.latest.true

Submitted June 29, 2020 at 06:43PM by raginimishra

What is the most common professional Node.js tech stack?

What is the most common Node.js tech stack used at companies? What database? What middleware layer? Any frameworks? Migration libraries? Modeling libraries?I see a lot of companies using Node.js on the back end in Job postings but curious as to what tools and frameworks they might be using.

Submitted June 29, 2020 at 04:51PM by maximusGram999

What's the best way to deal with unhandled async errors?

/r/learnjavascript/comments/hhq00r/whats_the_best_way_to_deal_with_unhandled_async/

Submitted June 29, 2020 at 03:13PM by ellusion

Why are devs using ES6 import instead of require in Nodejs ?

I keep seeing this pattern and I am wondering, Just why ?

Submitted June 29, 2020 at 02:47PM by goldenhunter55

AWS, Azure, GCP Or Firebase, Which One Would You Recommend Based On Ease Of Use?

I tried to learn AWS in order to create serverless node.js apps, but It's too complicated and overwhelming to the point where I ended up using a third party application called Serverless Framework.Even though Serverless Framework makes AWS easier "a little bit", You still have to use the AWS dashboard. The services are too many in the AWS dashboard to the point where every service is linked to each other which makes it even more completed.I know there are other services like Azure, GCP, Firebase e.t.c. If you have experience using any of these serverless services, which one would you recommend based on ease of use?

Submitted June 29, 2020 at 01:31PM by silverparzival

Papyr CMS - a jumping off point so you don't have to reinvent the wheel

Hello r/node,I have been working for a while on a project I have named Papyr CMS. Papyr is a content management system built on Next.js, making it an incredibly powerful web application for the end user and a easy to extend for the developer.Besides everything that comes packaged with Next.js, key features that come out of the box include:A quick initialization process once the site is running to create the admin user and first pageCustomizable contentA dynamic, extendable page builder and renderer for custom landing pagesA selection of commonly used page sections for the page builderUser authenticationSite notificationsBlogEventsEcommerceGoogle maps, Google analytics, Gmail, Stripe, and Cloudinary integration,Contact and donation formsWhile I did not hit everything in that list, many of those features are common and necessary for most web applications and websites, making Papyr a perfect jumping-off point to build an even more robust web application, or to simply spin up a quick website.You can visit the home website at https://papyrcms.herokuapp.com. Since great content is not necessarily my specialty, I have also created an example website with dummy content to show off more of what Papyr is capable of at https://drkgrntt.herouapp.com. Check out the code at https://github.com/drkgrntt/papyr-cms.While Papyr is designed to be super easy for developers to spin up a site and extend it easily, I have also tried to keep the non-developer client in mind as I build it. I have tried to keep it as simple as I can, but there is still the major issue of the setup process being non-dev-unfriendly (connecting to MongoDB and Heroku, etc). It is far from complete, but at this point, I feel like it is presentable and definitely usable.While I am mostly looking for feedback right now, if you think this is cool or useful, please feel free to clone and use it. Setup instructions are in the readme. I would love to answer any questions as well!Thanks for reading!

Submitted June 29, 2020 at 01:24PM by drkgrntt

Does anyone have a tool for converting Node projects from one case to another - e.g. kebab-case to camelCase?

I have a Node project where the files are all in kebab-case. I want to convert it to camelCase. So trasform file names and their references:Kebab case:import myFunction from "./app/my-function"index.jsapp/my-function.jsDesired camelCase:import myFunction from "./app/myFunction"index.jsapp/myFunction.jsI can create a script that will do this but it seems like something that someone has probably done but that won't appear at the top of any search results (I looked and found nothing). It's nothing more than file and string manipulation.Has anyone encountered a tool that can do this?

Submitted June 29, 2020 at 12:32PM by forgotusername14

Npm v7 release date?

Seems a lot of exiting features are about to land in v7. I can't seem to find any release date though.Is there any info on this ? I would really like to know, since it will save a ton of work for our team, migrating to yarn, since we want to use workspaces.

Submitted June 29, 2020 at 10:54AM by zarrro

Sunday 28 June 2020

How to eliminate ">" character from output buffer when using the "prompt()" from the "readline" package?

I need to make an application that takes input from the user in the following form:n k (two integers separated by space on one line)a b c d .... infinity(n integers separated by space on one line)My code accomplishes the task, but when I use the prompt function, node automatically prints on the output buffer a ">" character next to which I have to enter my input. I need to get rid of that, because my program's output is automatically being checked and parsed against expected output automatically.const readline = require('readline');const rl = readline.createInterface({input: process.stdin,output:process.stdout});let n;let k;let rezultatu;let numere=[];rl.question(``,                (userInput)=>{let vector=userInput.split(' '); //n and k separated by spacen=vector[0];k=vector[1];rl.prompt(); ////////////////////////////This is where it gets nastyrl.on('line',(userInput)=>{numere=userInput.split(' ');rl.close();                })                });

Submitted June 29, 2020 at 12:59AM by NaturallyElected

Mentor wanted: Google Cloud NodeJS

Hi, I am searching for a NodeJS tutor with specific knowledge working with the Google Cloud Platform. (GCP) I am looking to learn the Google Cloud while also learning the GCP. As a degreed engineer myself, I have a day job and hope that you would have professional level knowledge by either on the job or thru schooling. I am currently working on a couple of projects that were inspired by tutorials.Any thoughts on who might be interested in helping? Thanks.

Submitted June 29, 2020 at 01:02AM by wolfpackmike

Aprendiendo.js - Curso de Node.js gratuito en ESPAÑOL. En vivo todos los Martes 18hs (GMT-3)

https://www.youtube.com/playlist?list=PLX4T3u0vN5roedqreoDLQMDjOWXaMYNfE

Submitted June 29, 2020 at 01:04AM by kaminoo

Displaying node variable in browser

I have a Node js module that exports some data:module.jsmodule.exports = { data: "success!" }; My ultimate goal is to display this data in my browser. I have tried using Browserify to bundle the following js file:test.jsconst mod = require('./module') var data = mod.data; console.log(data); I bundle this to get bundle.js, then in my HTML file I have:index.html data:
"success!" is being logged to console, but I want it to be displayed on the browser. Any idea why the variable data is not recognized in my HTML page?

Submitted June 29, 2020 at 01:17AM by sphygmomanometer_

Axios : How to run multiple requests one after the other?

I have a very large array of IDs (thousands of IDs). I want to loop through this array and for each value, make a request to an API like so :javascript [12, 32, 657, 1, 67, ...].forEach((id) => { axios.get(`myapi.com/user/${id}`).then(({ data }) => { console.log(data.name); }); });However, I have so many requests to make I can't make them asynchronous because my computer has limits... Is it possible to wait for each request to be finished before making the next one ?

Submitted June 28, 2020 at 11:25PM by to_fl

Is there a tutorial to build a support live chat for a website using socket.io?

I would like to add a support live chat web app to my website using socket.io, mainly focused on new users who have specific questions or feedback about my product. All visitors of the website can chat with the support staff, currently me, but the visitors can not see each other's messages or communicate with each other. I looked around on the internet for a tutorial that goes through this but all were for communication amongst all the users like in a group chat like https://www.youtube.com/watch?v=rxzOqP9YwmM . However, I need to build one in which they can all individually only message me and can not read each other's messages or message each other, and I can reply to each message individually. Could you please link a tutorial that walks me through this or the code for such an app so that I can examine and understand the code?

Submitted June 28, 2020 at 10:11PM by Neighborhood_One

How to upload buffer image to cloudinary?

Hi,I want to upload an array of images to cloudinary. I've managed to parse the files with multer, that return them as buffer. After reading the documentation and github issues, it seems that converting the buffer to data uri is a performance killer. So I used the cloudinary' stream uploader, but it doesn't work.Here is my code:// multer config const storage = multer.memoryStorage(); const limits = { fileSize: 1000 * 1000 * 4 }; // limit to 4mb const upload = multer({ storage, limits }); cloudinary.config({ cloud_name: process.env.CLOUDINARY_CLOUD_NAME, api_key: process.env.CLOUDINARY_API_KEY, api_secret: process.env.CLOUDINARY_API_SECRET, }); // upload image router.post("/upload-images", upload.array("image"), ({files}, res) => { try { if (files) { const imagesUploaded = []; files.forEach(async (file, i) => { const image = await cloudinary.uploader.upload_stream(file, { resource_type: "image", public_id: `users/${req.userid}/img${i}`, crop: "scale", quality: "auto", }); return imagesUploaded.push(image.secure_url); }); console.log("imagesUpdated", imagesUploaded); // upload images url to the db } } catch (err) { return res.json(err); } }); Thanks!

Submitted June 28, 2020 at 08:25PM by MonsieurLeland

Getting Started with Node JS in 5 Minutes

https://www.youtube.com/watch?v=_h-pj7YqHQw&feature=share

Submitted June 28, 2020 at 08:11PM by jayanam

Response from api appears in the console but does not work in my function

Hello,So I have an api for testing fake user accounts with my auth code. I get the response and first console.log it and so far it has worked. But, more importantly, I need it to pass to my authenticate function. I'm not getting any errors for undefined or null. Additionally, I know the code works because I've tested it before with static json files. BTW I'm using the centra package for making http requests with my api.const c = require('centra');module.exports = {authenticate};async function authenticate({ username, password }) {c(process.env.API).send().then(response => response.json()).then(response => {console.log(response)const user = response.find(u => u.username === username && u.password === password);  if (user) {const { password, ...userWithoutPassword } = user;return userWithoutPassword;     }   }); }Is there any issue with my authenticate function? Thanks!!

Submitted June 28, 2020 at 07:14PM by LGm17

Kvell.js – Setup a production-ready Node.js app with batteries included

Hello everyone, I have always loved and admired the open source community and have always wanted to contribute something to it.Kvell is a family of packages using which you can create Node.js applications with pre-defined configurations, fixed application flow, and a set of abstractions. It bootstraps the node application with a set of popularly used npm packages and provides a minimal setup environment so that the developer can focus directly on writing the essential parts of the application.This is my first attempt at building something for the community and I will be happy to know what you think about it! If you like it, I would be glad if you can try it out. I am also open to any constructive criticism, so please let me know what can I do better as this is the first time I am trying something.Github: https://github.com/nsharma1396/kvellWebsite: kvelljs.now.shThank you

Submitted June 28, 2020 at 07:06PM by nsharma1396

Question about mongoose asyn validation

I am using mongoose and I have a problem when the async validation function, this is my code:https://pastebin.com/Dz7QLc5nBut when I pass an empty array for tags it just creates a new course with tags as an empty array like this{tags: [],date: 2020-06-28T15:53:43.379Z,_id: 5ef8bd07ec694c00dcd7bf5a,name: 'Javascript',category: 'web',author: 'mosh',isPublished: true,price: 15,__v: 0}​I tried the Promise.resolve() syntax from the documentation but it didn't work too, anyone have an idea why the validation for tags doesn't work?

Submitted June 28, 2020 at 05:14PM by Taro_Naza

A database software completely built as JSON files in backend. A powerful, portable and simple database works on top of JSON files.

https://www.npmjs.com/package/@syamdanda/json-base

Submitted June 28, 2020 at 05:16PM by syamdanda

Hosting 3 app's on one server.

First, I have 3 node app's:1) Front-end = Nuxt 2) Admin panel = Vue 3) RestAPI = ExpressI want to host them all on one droplet on digitalocean and access them via sub domains like: domain.com, admin.domain.com , api.domain.com.Second: Both front-end and admin panel has their own simple node backend to serve static files, is it ok to separate them or should the RestAPI also serve admin panel and front-end/client from the same server?Thanks in advance.

Submitted June 28, 2020 at 04:11PM by ouneahd

vscode breakpoints not being hit in TS mocha tests

Saturday 27 June 2020

How do you store images from Node App hosted on Digitalocean?

In case if i have ecommerce website and users upload images to server through node app (Ubuntu) is it ok to store images on server in images folder for example?Or should i set up something like cloud to store images?

Submitted June 28, 2020 at 07:17AM by ahdoue

How can I extract useful information from an onerror event in the websocket ws module?

ws_connection.onerror = (event) => { // websocket has encountered an error... log_msg('onerror event fired for ' + connection_name + ' with event of '+JSON.stringify(event)) } // end of ex[exName]['wsConn'].onerror = (event) => { The above code doesn't work...It gives the error that the event object contains circular references or something like that...How can I figure out what the event is that caused the error?Thank you.

Submitted June 28, 2020 at 07:04AM by grumpyThrifter

Using JSON with SQL

Hi y’all,So I’m using aws lambda to query a postgresql db, and I’m trying to use the event object to pass in params to the query. The problem is that the sql query needs a string with single quotes whereas the json param is a string in double quotes.Any ideas on how I can get around this ?Thanks

Submitted June 28, 2020 at 05:55AM by mejjaLezza

Google Cloud Firestore Nodejs Library (ts-datastore-orm) stable release

The library comes to a stable release after 6months+ testinghttps://www.npmjs.com/package/ts-datastore-ormts-datastore-orm targets to provide a strong typed and structural ORM feature for Datastore (Firestore in Datastore mode).Some code snippets:​import {BaseEntity, Column, Entity, datastoreOrm} from "ts-datastore-orm"; datastoreOrm.addConnection("default", {keyFilename: "serviceAccount.json"}); datastoreOrm.addConnection("production", {clientEmail: "", privateKey: ""}); @Entity() export class User extends BaseEntity { @Column({generateId: true}) public id: number = 0; @Column({index: true}) public total: number = 0; } @Entity({kind: "User", connection: "production"}) export class User1 extends BaseEntity { @Column({generateId: true}) public id: number = 0; @Column({index: true}) public total: number = 0; } async function main() { const user = User.create(); await user.save(); const id = user.id; }

Submitted June 28, 2020 at 04:53AM by plk83

find all userIds from object -> array -> objects

Hi, i am having problem to find out user ids fromconst userIds ={ "request" :[{"name" : "xyz","_id" : ObjectId("5ef6ab2b9c4b893b540f0077"),"userId" : ObjectId("5ef6aa259c4b893b540f0069")},{"name" : "abc","_id" : ObjectId("5ef7feb8b2bf75221088dfd6"),"userId" : ObjectId("5ef6aa6e9c4b893b540f006e")}]}console.log(userIds.request[0]._id) ---> gives only first idbut i want userId from all object. Can i get help

Submitted June 28, 2020 at 04:10AM by Manisha_987

Push Notification Question

Hi everyone.​I am working on an API wherein I need to be able to send notifications to an angular web client and react native android & iOS clients. I have got the push notification subscriptions working and I can send them and receive them on the client, however For my purposes I need to be able to send a notification to specific clients without them making a request since the notification will be in response to a server side event based on given times.​Is this even possible? do I need to look into web sockets? or is there something else I should be looking into.​Any insight is greatly appreciated!Thank you.

Submitted June 28, 2020 at 01:42AM by d0rf47

Best way to add some sort of randomized noise or visual on top of an image?

I'm trying to write some code that takes an image and adds some sort of randomly noise onto it, but I'm not sure about the best way to go about doing it. Many thanks!

Submitted June 28, 2020 at 12:40AM by Sayajiaji

best microservice architecture books?

Hi, guys, I want to master clean architecture for nodejs back end services: I use GraphQL; MongoDB; Express.any nice book to suggest?

Submitted June 27, 2020 at 10:25PM by iizMerk

Node.js app crashing when trying to download large files using it

I am trying to write a program that can convert HTTP URLs to torrents. This project is working basically working for download links contain small files. Like a file of 1-500Mb. My problem is if the file size is more than that the app is crashing or getting a timeout. So I want to know how to fix this. Below is link to my Github.https://github.com/savadks95/FireBitvar http          = require('http');var webtorrentify = require('webtorrentify-link');var fs            = require('fs');var url           = require("url");var path          = require("path");var validUrl      = require('valid-url');var express       = require('express');var getUrls       = require('get-urls');var remote        = require('remote-file-size');var app           = express();var downloadLink;var fileName;var fileSize;var server;var parsed;var param;var link;var port;port = process.env.PORT || 80;app.get('/favicon.ico', function(req, res){console.log('favicon request recived');});app.get('*', function(req, res){if(req.url==='/'){//app.use('/public/html', express.static(path.join(__dirname)));fs.readFile('public/html/index.html', function (err, data) {res.write(data);    });  }else if (req.url === '/l?thelink='){fs.readFile('public/html/emptyRequest.html', function (err, data) {res.write(data);res.end();  });}else{//---------Reciving Url--------------------console.log(req.query.thelink);downloadLink=req.query.thelink;//-----------------------------------------//------------checking for valid url-------if (validUrl.isUri(downloadLink)) {console.log('Looks like an URI');//-----------------------------------------//----------Extracting filename-------------parsed = url.parse(downloadLink);fileName = path.basename(parsed.pathname);console.log(path.basename(parsed.pathname));//-------------------------------------------//----------Finding File size----------------remote(downloadLink, function(err, o) {fileSize = (o/1024)/1024;console.log('size of ' + fileName + ' = ' + fileSize+" MB");  //-------------------------------------------if (fileSize <� 2500){///////////////Creating Torrent////////////////////webtorrentify(downloadLink).then(function (buffer) {console.log('creating the torrent');//res.send('what is');//-------------------------------------------res.setHeader('Content-Type', 'application/x-bittorrent');res.setHeader('Content-Disposition', `inline; filename="${fileName}.torrent"`);res.setHeader('Cache-Control', 'public, max-age=2592000'); // 30 daysres.send(buffer);console.log(fileName+'.torrent created');res.end();//-------------------------------------------});////////////////////////////////////////////////}else{console.log('More than 500 MB');res.send("

 More than 500 MB or invalid URL 

");}  });  }else {console.log('not url');fs.readFile('public/html/404.html', function (err, data) {res.write(data);res.end();});  }}});app.listen(port);console.log('server up and running', port);

Submitted June 27, 2020 at 09:25PM by savadks1818

Node: How to upload an image with formidable?

I want to upload multiple images to cloudinary. In my React client, I have a basic multiple files input. When I click on upload, the data is correctly sent. I use the library formidable on my server to parse the files and then upload them to cloudinary.Here is my client: uploadImages(files, 3)}/> The api request:export async function uploadImages(files, userid) { try { const images = new FormData(); images.append("fileSubmission", files[0]); const res = await ax.post( process.env.SERVER_URL + "/upload-images", images, userid ); return console.log("success", res); } catch (err) { console.log("error", err); } } And the server upload route:cloudinary.config({ cloud_name: process.env.CLOUDINARY_CLOUD_NAME, api_key: process.env.CLOUDINARY_API_KEY, api_secret: process.env.CLOUDINARY_API_SECRET, }); router.post("/upload-images", (req, res) => { try { const form = formidable({ multiples: true }); form.parse(req, async (_, fields, files) => { if (files) { const image = await cloudinary.uploader.upload(files, { resource_type: "image", public_id: `users/${req.userid}/${files.name}`, crop: "scale", quality: "auto", }); console.log("img uploaded", image.secure_url); return res.json({ image: image.secure_url }); } }); } catch (err) { return res.json(err); } }); It doesn't work. Would you know how to fix it? I know the server code misses a loop to upload all the files one after another. But when i did so, it said files.forEach is not a function. Anyways, this code still doesn't work even with a single image.The error is:TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type object at validateStringIf I console.log files once parsed by formidable, the result is:files { fileSubmission: File { _events: [Object: null prototype] {}, _eventsCount: 0, _maxListeners: undefined, size: 1813438, path: '/var/folders/hk/l5zpqnyh0000gn/T/upload_38a0a539fa77165b', name: 'filename.png', type: 'image/png', hash: null, lastModifiedDate: 2020-06-27T16:30:33.486Z, _writeStream: WriteStream { _writableState: [WritableState], writable: false, _events: [Object: null prototype] {}, _eventsCount: 0, _maxListeners: undefined, path: '/var/folders/hk/l5zpqnyh0000gn/T/upload_38a0a539fa77165b', fd: null, flags: 'w', mode: 438, start: undefined, autoClose: true, pos: undefined, bytesWritten: 1813438, closed: false } } } Thanks!

Submitted June 27, 2020 at 06:45PM by MonsieurLeland

How do I enter some data and get it on my page without reloading it?

I'm trying to build an app using NodeJS, in which user inputs data and this data is added to the content of the web page(in my case to the table) without reloading the page. Is there any ways to do it?P.S. I did post data with AJAX, but couldn't figure out how to get it without reloading. Then I thought about socket.io , but not sure if it's the solution.

Submitted June 27, 2020 at 06:46PM by b1vcksnvk3

How can I build a web chat app in which everyone can communicate with me but not each other?

Hi. I was trying to build a web chat application in which all the participants can not message each other but can only message me each individually and I can reply to them all individually (like a support chat). I tried researching and found a couple tutorials like https://www.youtube.com/watch?v=rxzOqP9YwmM but in this case it is a group chat and everybody can message each other and see each other’s messages. Could you point me towards a tutorial where it is explained how to build a chat application where people can only message me and not each other?

Submitted June 27, 2020 at 06:26PM by DefinitionSweet

Angular, JavaScript, CSS, Html, NodeJS quick Notes...

https://www.tutorialslogic.com/node-js?version.lat

Submitted June 27, 2020 at 05:11PM by raginimishra

await or promise.then in express rest api

router.get("/test", async (req, res) => {try{let result = await doSomethingAsynchronus();res.send(result);}catch (err) {res.status(500).send({message:err});}});​or​router.get("/test", (req, res) => {doSomethingAsynchronus().then(result)=>{res.send(result);}).catch(err=>{res.status(500).send({message:err});});

Submitted June 27, 2020 at 04:00PM by dc2015bd

Mongoose - Automatically add an object to array

Hi there folks,I have this code:newproject.findOneAndUpdate({ projectname: item }, {responsetime: [{timestamp: secondsSinceEpoch, pingtime: res.ping_time}]}).then(function() {console.log("Should have updated with timestamp and ping time!");});But the problem is that this overwrites responsetime and pingtime in the database. Any way I can make a new object instead of overwriting?My schema looks like this:var schema2 = new mongoose.Schema({email: "string",name: "string",projectname: "string",dashID: "string",pingStatus: "string",responsetime: [{timestamp: String, pingtime: String}],glitch: "boolean"})But I don't want to have to add a new object to the schema. I want this to be done automatically. (Should be [{timestamp: String, pingtime: String}, {timestamp: String, pingtime: String}] etc.) Any ideas on how to do this? Can you put me in the right direction (e.g. specific parts of docs about this)Thanks,Eddie

Submitted June 27, 2020 at 03:10PM by EddiesTech

Password hashing with NodeJS

https://www.loginradius.com/engineering/blog/password-hashing-with-nodejs/

Submitted June 27, 2020 at 03:28PM by mock_coder

How do I do authorisation and authentication for a blog without login register?

Im making a blog on node js with express how can I authorise myself as the admin without having the ability to login/register? Do you just hide the login page url? Is there another way to do it?

Submitted June 27, 2020 at 02:37PM by rDebate_Anything

Error handling best practices?

Hey guys, so what are your recommendations for handling errors for an api? What's the most efficient way, or what are the best practices? Many thanks!

Submitted June 27, 2020 at 02:17PM by EighteenthVariable

A minimal file tree based api router for building rest api's with node

https://github.com/barelyhuman/routex

Submitted June 27, 2020 at 11:04AM by aliezsid

I am trying to develop an API that manipulates video files to insert text and images into the video. Any API recommendations for that??

Users will upload videos of themselves answering some questions. The videos will be sent back to other users with the questions displayed on the video.I can't find any useful and easy to use APIs for that. Any recommendations??Thanks.

Submitted June 27, 2020 at 10:27AM by ertugrulucar

promise.all is running before for loop ends.

https://i.redd.it/6ps2dcno2f751.png

Submitted June 27, 2020 at 09:53AM by dc2015bd

Friday 26 June 2020

Best Typescript framework for jackbox-style websocket connection

I'm mainly a front-end dev, so I'm not too familiar with the backend framework landscape. I'm looking to build a server that can establish a 'session', which clients can connect to via a code (e.g. jackbox.io).My assumption is that I will need to create a new websocket server with a unique endpoint to establish a new session, and then open a client-side websocket connection to that unique endpoint. Is this accurate?So far I've been looking at Feathers.js, SocketCluster.io, Express.js and Nest.js, but I'm wondering what more experienced back-end devs would have to say.

Submitted June 27, 2020 at 06:04AM by Burned_FrenchPress

An admin gateway for Node.js API?

I’m creating a Node.js REST API. I was wondering if it is bad practice to create a client side admin dashboard for uploading files to the database within the Node.js app. I will eventually link the API with a React front end, but thought it might be useful to have a place where I can log in to upload data to the database.Is this something that’s bad practice? Are there other optimal ways of doing this? I’m also thinking it can be done through a admin login within React.Any thoughts and advice would be much appreciated!Thanks!

Submitted June 27, 2020 at 12:57AM by intrepidvariable

How to set up a local development server?

My app has gotten to the point where it isn't feasible to rebuild everything on my desktop after making a tiny change (if I have VSCode running....).I have a laptop (running Ubuntu) that I'd like to use as a development server.My ideal setup is all of my code is hosted on a local network and every change i make on my desktop is automatically picked up by my laptop which then builds the project. I can then commit the local changes to git once ready.Wondering if anyone can point me in the right direction of how to get this set up?

Submitted June 27, 2020 at 12:39AM by nickkang1

Performance issue in function parameters binding

Hi everyone, I discovered a performance issue in my Node.js application due to function binding: I have to attach several helper functions to an object, each function has some parameters to be bound but I found out that using the bind method causes my application to slow down by about 30%.Is there an alternative to the bind method that allows me to set the "this" context and some additional parameters?Here you are the the piece of code where binding happens:​// Get all the helpers registered under the given namespace. const helpers = super.getAll(namespace); const bind = options !== null && Array.isArray(options.bind) ? options.bind : [this]; if ( options !== null && options.context !== null && typeof options.context === 'object' ){ // Context variables have been defined, add them as the first argument of the helper function. bind.splice(1, 0, options.context); } // Inject helper functions. // OPTIMIZE: Binding is slow, find a better alternative. for ( const name in helpers ){ if ( helpers.hasOwnProperty(name) ){ obj[name] = helpers[name].bind(...bind); } } ​If you need, here's the full class code (method: static inject):https://github.com/RyanJ93/lala.js/blob/master/lib/Helpers/HelperRepository.jsOne of the places this binding is required (method: async process):https://github.com/RyanJ93/lala.js/blob/master/lib/Server/processors/HTTP/HTTPRequestProcessor.jsAnd here some helper function examples (the whole file, list at the bottom side):https://github.com/RyanJ93/lala.js/blob/master/lib/Server/helpers/HTTPRequestProcessorHelpers.js​Thank you in advance.

Submitted June 26, 2020 at 11:45PM by RyanJ93

Sequelize ORM

const User = sequelize.define('User',{name: DataTypes.STRING(99),email: DataTypes.STRING(99),password: DataTypes.STRING,active: DataTypes.BOOLEAN,},{tableName: 'users',hooks: {beforeSave: async (user) => {if (user.password) {user.password = await bcrypt.hash(user.password, 8)}},},})User.associate = function (models) {console.log(models)User.belongsToMany(models.Clinica, {foreignKey: 'user_id',as: 'clinicas',through: 'users_clinicas',})module.exports = UserThis code always return: Association with alias "clinicas" does not exist on UserWhen I run:User.findAll({include: [{association: 'clinicas',where: {id: 1,},attributes: [],},],attributes: ['id', 'name', 'email', 'profile_id'],logging: console.log,})

Submitted June 26, 2020 at 11:29PM by gofgohorse

Redux with node simple practice project to learn redux flows

https://github.com/design2soft/redux-with-node

Submitted June 26, 2020 at 10:09PM by langagnostic

How to Debug a Node.js Application with VSCode, Docker, and your Terminal

https://www.freecodecamp.org/news/node-js-debugging/

Submitted June 26, 2020 at 09:29PM by erickwendel_

Creating an Application Performance Monitor Using Node 14 New and Experimental Features

https://medium.com/@erickwendel/node-v14-x-is-up-deep-diving-into-new-features-ace6dd89ac0b

Submitted June 26, 2020 at 09:09PM by erickwendel_

getting api result value outside then function

Hi, I am new to nodejs and an facing an issue with request promise. I am running an API but I am not able to get the result of API out of then function.My code is as follows.var rp = require('request-promise'); var options = { uri: "URL", json: true }; rp(options) .then(function (body) { console.log(body); const data = body; }) .catch(function (err) { // API call failed... }); ## I want to print my api body here Thanks in advance

Submitted June 26, 2020 at 08:53PM by alpha2311

My first ever NPM package - Express-JMESRange (JMESQuery based range filters for json endpoints)

https://www.npmjs.com/package/express-jmesrange

Submitted June 26, 2020 at 07:01PM by macca321

Generic repository in Typegoose? Typescript. Mongodb.

[Question] Does mLab's Shared Cluster $15 plan support transactions?

Hello everyone, I hope you're doing great.I just started learning Node and MongoDB recently. I'm trying to create a simple API for which I need MongoDB's transactions. But from what I understood is that, transactions only work if there are more than one replica set? The project is pretty small, so I will deploy it on mLab's Shared Cluster $15 plan. The plan's description says: "This plan is a multi-node replica set cluster..."My question is, can I use transactions if I subscribe to that plan? Because I got confused with all the differences between replica sets, shards, and clusters.Thanks in advance.

Submitted June 26, 2020 at 05:20PM by diebxlue

Socket.IO randomly won't establish connection

So I'm getting the below console error on multiple browsers that I've tried (they all say the same error in different ways)Firefox can’t establish a connection to the server at ws://localhost:3001/socket.io/?EIO=3&transport=websocket&sid=L1kIMe8FN7IyhGVYAAAA.The sockets work sometime even when I'm getting the errors, and sometimes I'm not even getting the error at all...I use react for the front and of course NodeJS for the back..I'd love to get some help with this issue :)

Submitted June 26, 2020 at 04:28PM by s_trader

Question about Node framework

Hi, hope you all fineI'm looking to start a project in Node, i used Laravel several times and I like a lot that framework, so I'm looking a solution as robust as Laravel, but in the Node. So I found hapi and expressjs, this last is specially the one that most convinced me, but, it's a good use expressjs for real professional projects?

Submitted June 26, 2020 at 03:40PM by Eli_Road

How to get an object field as an array in mongoose?

Hi guys, I have a mongoose schema like the following,const followingFollowersSchema = mongoose.Schema({ follower: { type: mongoose.Schema.ObjectId, ref: 'User' }, following: { type: mongoose.Schema.ObjectId, ref: 'User' }, }); I have created a route when called it filters all the users that the current logged in user is following and shows the following output,{ "status": "success", "results": 1, "data": { "following": [ { "_id": "5ef4cd0205070d87156e19da", "following": { "_id": "5eeb92d69fceed6d91ad5743", "name": "X Y" } } ] } } But I want to show the output like this,{ "status": "success", "results": 1, "data": { "following": [ { "_id": "5eeb92d69fceed6d91ad5743", "name": "X Y" } ] } } How can I accomplish this? Any help would be appreciated.

Submitted June 26, 2020 at 03:03PM by Baldy5421

Which packages can replace the hapi framework that is scheduled for deprecation?

I had just stared working on a new API when I learned that hapi is scheduled for deprecation.Migrating to hapi from express has been a blessing for simpler projects because authentication and validation (using joi) was natively and, more importantly, elegantly supported. Same applies to unit testing using lab and code.I’ve spent a few hours trying to put together an equivalent stack "à la carte" on express and things don’t feel right. FYI, I am using TypeScript.Currently, I am considering using express, express-validator, passport and supertest as alternatives... Is this a descent replacement stack? I am a little disoriented.I have no problem with express, but the semantics of express-validator isn’t as clean as joi.```javascript // ...rest of the initial code omitted for simplicity. const { body, validationResult } = require('express-validator');app.post('/user', [ // username must be an email body('username').isEmail(), // password must be at least 5 chars long body('password').isLength({ min: 5 }) ], (req, res) => { // Finds the validation errors in this request and wraps them in an object with handy functions const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(422).json({ errors: errors.array() }); }User.create({ username: req.body.username, password: req.body.password }).then(user => res.json(user)); }); ```This is the part I dislike the most... I would like to abstract this logic once instead of adding it to all handlers.javascript // Finds the validation errors in this request and wraps them in an object with handy functions const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(422).json({ errors: errors.array() }); }Ideas? How are you guys handling this on Express? And what stack are you using or considering using to replace hapi?Sending my love to Eran for outstanding (and certainly exhausting) work.

Submitted June 26, 2020 at 03:17PM by sunknudsen

Thursday 25 June 2020

What data should I store on Redis?

From what I understand, you should store in Redis information that is often requested, but not every single query to the database, since Redis storage can be expensive.This is why I'm not sure what should I store on Redis. Let's say I'm creating Reddit, what should I cache?. User info seems pointless since no one is going to request it that often, and specific subreddits depends on the user or the number of people that are going to be visiting it. Maybe storing most popular subreddits?All I want is some examples, thanks in advance!

Submitted June 26, 2020 at 06:54AM by Ivaanrl

How to restart forever-service?

Can anyone share what your email queuing system looks like? Examples online directly use nodemailer, yet to find one using a queue

User signs up/forgets password etc you need to send an emailAfter spending almost a day googling and going through examples, most of them directly use the nodemailer to sendEmailIf I am not mistaken, arent you supposed to queue emails so that your server doesnt get clogged?I havent been able to find even a single decent example of how to queue emails?I found this package called bull but what does the workflow look like?Add only addresses to this queue?Add addresses + subject + text of the email to queueAdd link to a SES template?How is this queue object passed to the route? globally? as an argument to a functionCan someone kindly share some idea of how the design pattern would be for this problemIs this testable by Jest?

Submitted June 26, 2020 at 06:48AM by amazeguy

Looking to see if this type of library exists?

/r/webdev/comments/hft646/looking_to_see_if_this_type_of_library_exists/

Submitted June 26, 2020 at 05:09AM by kingducasse

What is buffer in Node js?

please someone tell what is buffer in node js in a simple way possible

Submitted June 26, 2020 at 03:29AM by Deepanshu188

What cli tools can I use to do some security audits on 15 repos?

I have 15 node.js repos and I need to do some basic security audits. Are there any CLI tools I can run on the codebases? (Ubuntu)

Submitted June 26, 2020 at 03:15AM by chovyfu

Im starting to implement APIs but i really don't know how to work with a public API for my backend practice

So right now im practicing with the Pokeapi and on the backend side of things i want to save 6 pokemon per team(each user can have multiple teams) but right now im blackout in my head so i can use the help, i don't know how to proceed.. I want to know how am i going to be able to retrieve the data from the pokeapi to my backend to do the teams with the pokemon and all of that data.If you guys can give me any documentation/videos/tutorials that would be a lot of help and thank you

Submitted June 26, 2020 at 02:12AM by CarlosCazun

Would you build SaaS with NestJS in 2020?

Nest seems to be quite popular these days. I'm still in the process of exploring it and haven't made up my mind yet. For a current SaaS project, I find myself asking:Should I use NestJS to built SaaS in 2020? What will be the advantages and disadvantages (especially for the SaaS space)?I'm very excited to hear your opinions!

Submitted June 25, 2020 at 06:56PM by memo_mar

Using node.JS to help create a website that uses data from other websites? need help, so lost.

So, I'm currently doing a Web Dev bootcamp, I'm about halfway done and I'm trying to come up with a personal project to challenge myself and also have something useful that'll stand out. Anyways,I have this odd hobby of monitoring everyone who's been arrested per week in Hillsborough County FL. Sometimes if I see an old friend who has been arrested, I immediately go to the clerk of court website for Hillsborough county and look at their court case and even get their CRA(Criminal Report Affidavit) aka Police Report redacted so I can see what they actually did. I'm really big into all of this, call it weird but I got sick of having to look up the arrest on florida.arrests.org or fromwebapps.hcso.tampa.fl.us/ArrestInquiry and then having to go immediately to hover.hillsclerk.com to search court records and all court info regarding said person. I thought it'd be cool to construct a website where on the index page it's just 2 textboxes and 1 submit button. 1 text box being for First Name and the second being for Last Name. Once submitted, the First and Last Name are compared to a database and all arrests for Joe Macgyver come up and Joe Macgyver's court cases(open and closed) which include court dates, evidence submitted by the state, basically everything that happened in court on whatever day. So all arrests for Joe Macgyver in Hillsborough county come up and on the same page all court cases. I figured it'd be cool and it'd save me some time but I don't even know where to begin.It looks like florida.arrests.org is gonna be more practical than webapps.hcso.tampa.fl.us/ArrestInquiry because they just recently made some changes and the sheriff's office is only allowing arrests within a 3 month time period to remain public record that can be accessed for free online. They also have a captcha that needs to be entered for every search done However, Florida.arrests logs every arrest made and doesn't delete anything and has records going back to the late 90s. I can't seem to find any way to get an API key for florida.arrests.org so I know its possible to do what i wanna do, I just dont know where to start and how to go about it. A friend suggested web scraping, I did some research and got a little confused. Can anyone possibly help point me in the right direction? I figured if I kept the searches down to only hillsborough county, it should make my idea a little easier.Thank you,FLPapo

Submitted June 25, 2020 at 07:04PM by FLPapo

Help with async recursive function

const getComments = async (commentData) => {if (!Array.isArray(commentData.data.replies)){console.log("bottom");return [commentData.data.body];    } else {for (reply of commentData.data.replies.data.children) {const tempComments =  await getComments(reply);tempComments.push(reply.data.body);console.log("step");return tempComments;      }    }};I'm using this on json I get from Reddit comments. Each comment has an array of replies unless it's the last comment in the thread. When it hits the last comment in the thread it returns that body. And then I want it to all the way back up the thread adding the comment of the body to an array and at the end have an array of comment bodies from threads. Am I calling this recursive function wrong?

Submitted June 25, 2020 at 06:27PM by laneherby

Learn to upload files using Multer and Noje.js in just 5 minutes

https://www.hotreloader.com/2020/06/upload-using-multer-and-nodejs.html

Submitted June 25, 2020 at 03:57PM by navvsinghh

Deploying to Github Pages? Don't Forget to Fix Your Links

https://maximorlov.com/deploying-to-github-pages-dont-forget-to-fix-your-links/

Submitted June 25, 2020 at 03:29PM by _maximization

Redirecting on clicking Login with Google button using Passport-Google oAuth2 and Express, React

Right now, I want that:Whne user clicks on Login with Google button, gets redirected to the oAuth consent screen.In the consent screen, when the user chooses the account, it gets redirected to the route /auth/google/redirect(is this the correct route?) which logs in the user. So, then I want to set a cookie which I'm doing in app.js. This shows that the user is logged in.Now, how do I make a request from the NavBar component in my react frontend? For now, I have a button. I want to know the process that happens when I click the button; which backend route should I call?I'm having real trouble. Please suggest me some resources or help me understand it. Thanks.routes/auth.js```js const express = require("express") const passport = require("passport") const auth = require("./controllers/auth") const router = express.Router()// auth with google router.get("/google", passport.authenticate("google", { scope: ["profile"] }))// callback route for google to redirect to router.get("/google/redirect", passport.authenticate("google"), (req, res) => { // what to do here????? })module.exports = router ```config/passport.js```js const passport = require("passport") const GoogleStrategy = require("passport-google-oauth20").Strategy const User = require("../models/User")passport.serializeUser((user, done) => { done(null, user.id) })passport.deserializeUser((id, done) => { User.findById(id).then((user) => { done(null, user) }) })passport.use( new GoogleStrategy( { clientID: process.env.clientID, clientSecret: process.env.clientSecret, callbackURL: "/auth/google/redirect", }, (accessToken, refreshToken, profile, done) => { // check if the user exists User.findOne({ googleID: profile.id }).then((currentUser) => { if (!currentUser) { // if the user doesn't exist; create a new user new User({ username: profile.displayName, googleID: profile.id, }) .save() .then((newUser) => { console.log(`New user created- ${newUser}`) done(null, newUser) }) } if (currentUser) { console.log(`The current user is- ${currentUser}`) done(null, currentUser) } }) } ) ) ```NavBar.js```jsimport React from "react"const NavBar = () => { return ( // is this the correct URL??? //how to handle onClick here ) }export default NavBar ```app.js```js app.use(cookieSession({ maxAge: 24 * 60 * 60 * 1000, keys: [process.env.cookieKey] }))// intialize passport app.use(passport.initialize) app.use(passport.session) ```

Submitted June 25, 2020 at 03:34PM by Snoo10987

Better understanding of Axios handling of httpOnly cookies

I've developed a Flask backend and am experimenting with a JavaScript frontend. I am much less familiar with JS than backend issues. I was able to spin up a simple CRUD API in Flask. After learning about Bearer JWT in LocalStorage vs httpOnly Cookies, I figured that httpOnly Cookies were a good way to go.After about a month of banging my head against the wall and looking at forums, I finally broke through, but I don't fully understand why this works. Can someone help me out? I've got questions.So first off { withCredentials: true} is not magic. There are lot of posts that suggest it-just-handles-it™. However, while I was able to log in and see in my console.log the cookie was set correctly, I could not figure out how to pass the token to the backend on the next GET request. Perhaps this is just for Authorization headers only or Basic Auth? Do I still need to include it?Is parsing the cookie standard? Should the token be persisted in LocalStorage? This seems to defeat the purpose of an httpOnly cookie, right?It's become clear that sending the credentials to my Flask backend require modifying the axios interceptors to send a custom header. axios-token-interceptor seems like a good library to help with this. Are there other libraries or recommended ways to do this?Anything else I should be thinking about?const http = require('http'); const axios = require('axios'); const tokenProvider = require('axios-token-interceptor'); var cookie = require('cookie'); const hostname = '127.0.0.1'; const port = 80; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World'); }); const instance = axios.create({ withCredentials: true, baseURL: 'MY-URL', mode: 'cors', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' } }) instance.post('/auth/login', { 'username': 'USERNAME', 'password': 'PASSWORD' } ) .then((response) => { console.log(response.data); const cookies = cookie.parse(response.headers['set-cookie'][0]); console.log(cookies); // console.log(response.status); // console.log(response.statusCode); // console.log(response.statusText); // console.log(response.headers); // console.log(response.config); setTimeout(function(){ instance.interceptors.request.use(tokenProvider({ token: cookies.access_token_cookie, header: 'Cookie', headerFormatter: (token) => 'access_token_cookie=' + token, })); instance.get('ENDPOINT', { withCredentials: true},) .then((response) => { console.log(response.data); }); }, 4000); }) server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });

Submitted June 25, 2020 at 03:19PM by chasetheskyforever

Error when i try to run Webpack to include React. MERN stack.

https://i.redd.it/kd89tksfx1751.png

Submitted June 25, 2020 at 01:42PM by LittleTower_

How to login in gmail using puppeteer without getting blocked?

I've been trying any solutions i've found on the internet but unfortunately nothing works yet.These are some of the solutions from these links https://github.com/puppeteer/puppeteer/issues/4871https://github.com/puppeteer/puppeteer/issues/4732i'm just starting with puppeteer so i don't know what's the problem. I've read that google sort of blocks this kind of scripts.I've tried 2 different solutions based on what i've searched but nothing works yet.Attempt 1: ``` const puppeteer = require('puppeteer-extra'); const StealthPlugin = require('puppeteer-extra-plugin-stealth');puppeteer.use(StealthPlugin());const dotenv = require('dotenv');dotenv.config();async function run() { const browser = await puppeteer.launch({ headless: false, slowMo: 50, });const page = await browser.newPage(); await page.goto('http://accounts.google.com');const navigatePage = page.waitForNavigation();const email = 'input[type="email"]'; const password = 'input[type="password"]';await page.waitForSelector(email); await page.type(email, process.env.EMAIL); await Promise.all([page.keyboard.press('Enter')]);await page.waitForSelector(password); await page.type(password, process.env.PASS); await Promise.all([page.keyboard.press('Enter'), navigatePage]);await page.screenshot({ path: 'testresult.png' }); await browser.close(); }run(); ```This one is another solution that i did: attempt #2 ``` const puppeteer = require('puppeteer'); // const puppeteer = require('puppeteer-extra'); // const pluginStealth = require('puppeteer-extra-plugin-stealth'); // puppeteer.use(pluginStealth()); const chromeLauncher = require('chrome-launcher'); const axios = require('axios'); const Xvfb = require('xvfb');const xvfb = new Xvfb(); xvfb.startSync(); const chromeConfig = { // chromePath: '/usr/bin/google-chrome', userDataDir: '/home/chan-dev/.config/google-chrome/Default', };async function launch() { const chrome = await chromeLauncher.launch(chromeConfig); console.log({ chrome }); const response = await axios.get( http://localhost:${chrome.port}/json/version ); const { webSocketDebuggerUrl } = response.data;const browser = await puppeteer.connect({ browserWSEndpoint: webSocketDebuggerUrl, });const page = await browser.newPage(); await page.goto('http://accounts.google.com');const navigatePage = page.waitForNavigation();const email = 'input[type="email"]'; const password = 'input[type="password"]';await page.waitForSelector(email); await page.type(email, process.env.EMAIL); // await Promise.all([page.keyboard.press('Enter')]); await page.keyboard.press('Enter');await page.waitForSelector(password); await page.type(password, process.env.PASS); // await Promise.all([page.keyboard.press('Enter'), navigatePage]); await page.keyboard.press('Enter');await page.screenshot({ path: 'testresult.png' }); await browser.close(); }launch() .then(() => console.log('ok')) .catch(err => console.error(err)); ```

Submitted June 25, 2020 at 10:52AM by theUnknown777

Top 10 List Of Node.Js Frameworks for 2020

https://kodytechnolab.com/top-10-node-js-frameworks

Submitted June 25, 2020 at 10:52AM by SachinKody

hapi will not be supported anymore by the end of the year

https://twitter.com/hapijs/status/1275887984114413569

Submitted June 25, 2020 at 09:14AM by ecares

Binary Search Using Recursion.

https://youtu.be/OxaCW5ZB700

Submitted June 25, 2020 at 07:29AM by okaydexter

Wednesday 24 June 2020

IMAP in node.js? How can I receive emails with a node.js app?

I am aware of nodemailer which is for sending email, but I'm wondering what to use to receive emails.I have come across mailin which hasn't been updated in 3 years.And node-imap, which seems active now, but isn't a big repo.My concern is that I'm not sure if either of these are reliable enough for an app I intend to make and run for a long time.

Submitted June 25, 2020 at 06:26AM by tiddysiddy

Toronto Tech Scene

https://npmjs.com/toronto-tech-scene

Submitted June 25, 2020 at 04:32AM by kahlontej90

setup-express-app tool

Hello everyone, i just published my first nodejs script that generates new express skeleton project for building APIs. It automatically installs most used dependencies for creating express based APIS and writes boilerplate codes to the generated files. Your contributions and suggestions are highly welcome. https://www.npmjs.com/package/setup-express-apphttps://github.com/abdul-razaq/setup-express-app

Submitted June 25, 2020 at 04:50AM by ant1g3n

What's the best Socket IO chat application tutorial?

There are thousands of tutorials showing you how to make a chat application. So I would like to take the best course instead of wasting my time doing them all. What's the best Socket IO chat application tutorial?

Submitted June 25, 2020 at 04:53AM by torrentstorm

Can you use VAPID keys for email verification?

My thought process:Generate and save private and public vapid key at registration phasesend an email with the public vapid keywhen the user clicks the link the he/she sends the public vapid key as request parameterfinally I check for the public vapid key and match it with the private and activate his/her account

Submitted June 25, 2020 at 03:41AM by ajirnanashak

TypeScript project generator

Hi there, I've publish an npm package that may help you to initialize a new Node.js project with TypeScript. Give it a try!

Submitted June 25, 2020 at 02:59AM by anthonylzq

Microservices and newer technologies for dummies? Going out of the loop

I am a passionate Node developer and I'd like to learn more about microservices and newer technologies which usually are used in stacks including Node.My main concern is going out of the loop; just to make a simple example which doesn't fit in the microservices theme, yeah, I can understand newer things like NoSQL databases, but I can't grasp things like Elasticsearch, Cassandra and other things I consider "weird", like GraphQL, Docker, Kubernetes and all of that.I'm trying to go out of my actual common standards (FTP dedicated servers monoliths using Express + MariaDB + Redis, or Koa + MongoDB + Redis, or mix'em), because I'd like to learn new things, but you know, everything seems a big mess to a developer coming from such a strict background.I can't understand in any way how would microservices be implemented in Node, even though I tried to look to express-gateway and moleculer (I like the first more because I'd like to convert a monolith server which uses Express to a distributed one).For example, I understood that microservices communicate to each other using REST - but wouldn't that be slower? Also, how should developers keep links of microservices' APIs; when changing one microservice's machine or domain, should also all other microservices change with the new API path? What the heck gateways are? And why do we need them?There are lots of questions I'd like answers to, and I think those aren't Node related questions, so I'll just avoid asking in this subreddit - that's not my point.My point is, everything seems so complicated, and there's no article, book, guide which clarifies things for noobies like me, and starters in this distributed-cloud-and-everything world.How can I learn something more?Are there any good articles for beginners which point out how microservices in Node could work?Or maybe any way to keep interest in things which are explained soooo bad online to me? (yeah, I'm more a practical learner, maybe it's because of that).

Submitted June 25, 2020 at 03:00AM by DanielVip3

Underware: Whitey Tighties

Underware RepoJust released the first version. I've been using this project, but in the private scope. I decided to make it publicly usable, and would like to get some eyes on it for a sanity check.

Submitted June 25, 2020 at 02:39AM by IroncladFool597

Egg js?

Anyone use it before? Experience?

Submitted June 25, 2020 at 02:45AM by ineedhelpcoding

Add JS functionalities to a nodejs express app (slideshow)

I am new to nodejs and I am working on a milestone project. I am using NodeJS, Express, and MongoDB. I had vanilla JS code that was retrieving dummy data and manipulating the HTML through the DOM. I understand I cannot use DOM through an express app. Where would I begin to do the same thing with express? I want to retrieve data from mongoDB and when I click a button on my html retrieve post[i].title and post[i].contentfunction currentPost(n) { post1= '

Post 1

"Lorem ipsum dolor"

'; if (n == 0) { document.getElementById("containerBlogPost").innerHTML = post1; } else if (n == 1){ document.getElementById("containerBlogPost").innerHTML = post2; } else if (n == 2){ document.getElementById("containerBlogPost").innerHTML = post3; } else if (n == 3){ document.getElementById("containerBlogPost").innerHTML = post4; } } On an event I was using that data to upload my html using the DOM. I don't need ridiculous details but I need guidance. I have been struggling with this all day.

Submitted June 25, 2020 at 01:59AM by Prestigious_chestnut

NodeJS - Javascript functionalities (such as a slideshow)

I'm new to NodeJS and I am building a project as a milestone using NodeJS, Express, and MongoDB. I previously had this same project on a local server. I am struggling converting my vanilla JS that interacted with the html through DOM into an express module that will manipulate the html using the database from mongoDB. As an example I had an li of buttons that responded with each post.​post1= ({title: "test", content:"I am struggling"});​function currentPost(n){if (n == 0) {    document.getElementById("containerBlogPost").innerHTML = post1;    }else if (n == 1){    document.getElementById("containerBlogPost").innerHTML = post2;    }else if (n == 2){    document.getElementById("containerBlogPost").innerHTML = post3;    }else if (n == 3){    document.getElementById("containerBlogPost").innerHTML = post4;    }}How can I manipulate the html to grab this data to still use those buttons to switch between posts? I really need some help :(

Submitted June 25, 2020 at 01:16AM by Prestigious_chestnut

Exit Code 3221225725, when looking at the issue on github it said to change node-sass version, I did it didn't fix the issue. Would like help

Building a Backend for React with Next.js, Prisma 2, and Postgres

https://youtu.be/Bqacj0iOL68

Submitted June 24, 2020 at 09:39PM by monosinplata

Cant modify homepage html and js file once user logs in through the server

Hi everyone, i've been working on a project in which users can upload csv, text files or excel and i show them using chartjs, everything has been fine up until now when i bumped into this issue in which i cant seem to find a way to make changes to the main html and app.js files once i get the login information correctly, my idea was redirecting the user to the updated homepage where the submit file button is allowed once you bypass the login. In case anyone is interested in helping me i will leave my github page https://github.com/Rogerpeke97/Csv-file-converter. Here is a snippet of the server side code: Im using postgresql, expressjs, multer and chartjs as dependencies.​const express = require('express'); const app = express(); const fs = require('fs'); const multer = require('multer'); const path = require('path') const { Pool, Client } = require('pg'); const bodyParser = require("body-parser"); const PORT = 5000; //Set static folder: use is a method that we use when we want to include middleware app.use(express.static(path.join(__dirname, '/'))) /* Way to get file manually instead it´s easier to create a static folder app.get('/', (req, res) => { res.sendFile(path.join(__dirname + '\\index.html')) });*/ app.listen(PORT, () => console.log("Server started on port " + PORT)); //upload file multer let storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, path.join(__dirname, '/')) }, filename: function (req, file, cb) { cb(null, file.originalname) } }) let upload = multer({ storage: storage }) app.post('/uploadedfile', upload.single('myFile'), (req, res, next) => { const file = req.file if (!file) { const error = new Error('Please upload a file') error.httpStatusCode = 400 return next(error) } res.send(file) }) app.use(bodyParser.urlencoded({extended: true})); //getting these values and using them in functiuon userConnect() down below let usernamE = []; let passworD = []; //use function userConnect() to submit data into table //Here i tried to add an html tag to show if login was succesful but it failed //if login was correct it would redirect but im not sure how to change //html contents once i redirect to the home page again app.post('/', async function loginSuccess(req, res){ let b = req.body.myFile; res.redirect("http://localhost:5000") }) app.post('/', async (req, res)=>{ let username = req.body.uname; usernamE.push(username); let password = req.body.psw; passworD.push(password); userConnect(); res.end(); }); //Postgresql const client = new Client({ }) async function userConnect(){ if(usernamE != null){ client.connect(); const text = 'SELECT * FROM users where first_name = $1 and password = $2' //const text = 'insert into users (first_name, password) VALUES($1, $2) RETURNING *' const values = [usernamE.toString(), passworD.toString()] client.query(text, values, (err, res) =>{ //when user doesnt exists postgresql responds with an empty array //thats why i added the length < 3 if(res.rows.length < 3) { loginSuccess(); } else{ console.log(err.stack) } }) } } // callback async ​

Submitted June 24, 2020 at 09:22PM by rogerpeke97

PERN Stack: Build a full stack YELP clone

https://youtu.be/7qAXvOFhlDc

Submitted June 24, 2020 at 09:13PM by sloppy_networks

Connecting to the db during unit testing

Is it a bad practice to do real db connection in unit tests ? and if so what is the best practice ?

Submitted June 24, 2020 at 08:29PM by mogtba_hassan

Is it possible wrap a node web app into a mobile app?

I’ve developed a node.js web application using bootstrap and javascript. I’ve been asked if it’s possible to turn the website into a mobile app, I know that it is possible to use webviews, but I don’t really know what that entail as I’m not fluent in app developing yet. Is it possible to embed a node web app into a mobile app (android/iOS) and make it work even without internet? What are the requirements?

Submitted June 24, 2020 at 07:40PM by Artemis_21

Save report filters and making it available for executing and scheduling

Hello Node Community,I have a use case where I have to Add query params to APIs call, and save it accordingly. Meaning- I have one report to Add, which gives multiple filters that to be saved. (Some of them are pre-defined and others can be added) which could be saved and it could run to generate report or to schedule it. How here I am using postgres sql as DB. How can I solve such scenarios, If say saving into db then what's the best way to do such operations? I have a db table where I am storing Report name and descriptions. But how can I add such Filters and Save it? And next time the user just Schedule or generate report with saved filters.Below are the images for better understanding of the scenario.​The Image of where List displayed of saved reports 📷https://preview.redd.it/5st6wq39rv651.png?width=2176&format=png&auto=webp&s=0bff8719e6dd325913f587263fd28194a2fd46ebThe Image where user can Add custom report using available filters.https://preview.redd.it/7ykvvqfbrv651.png?width=1168&format=png&auto=webp&s=982d4b817ab3a0f8b7ff3fc2ffb8cf83e91b1f71Not sure the best way to handle such scenarios, where I have to add multiple of filters and save it accordingly.Can anyone help me here with the approach to handle such things? Like saving in DB or how it could work the best. ThanksRelatable Example - Something like JIRA, can save the filters and directly apply it. Something like this.

Submitted June 24, 2020 at 04:56PM by farhan_721

Dependency injection container with NodeJS

https://therebelsource.com/blog/dependency-injection-container-with-nodejs/1~pOi9oTxwe

Submitted June 24, 2020 at 05:07PM by SnooDrawings7133

Help needed receiving get request - Express

[Express JS] How To Allow only my IP address and my website's IP address to access my API?

Hello,I want to know how would I go about making so that people cannot just access my public API easily. The only way to access it would be if the request is coming from my home IP address or the IP address of my website which requests the API for data?If anyone can point me in the right direction that will be much appreciated : )Thanks in advance.

Submitted June 24, 2020 at 04:10PM by nebling

Deploy your Node apps in seconds and for free

https://deta.sh/micros

Submitted June 24, 2020 at 04:10PM by randomtty

Using `import` Statements in Node.js - Mastering JS

https://masteringjs.io/tutorials/node/import

Submitted June 24, 2020 at 03:12PM by code_barbarian

New to ExpressJS. Why does this basic request print twice?

Hi all,I just started learning about Express and middleware. I have the following code:"use strict" var express = require('express'); var app = express(); // allows you to work with file and directory paths var path = require('path'); app.get('/', log, hello); function log(req, res, next) { // THIS ALWAYS GET PRINTED TWICE console.log(new Date(), req.method, req.url); next(); } function hello(req, res) { res.write('Hello'); res.end(); } app.listen(3000, function() { console.log('Web server is listening on port 3000') }) Basically, I have a an app.get() that calls the log and hello functions on the request. Despite the log function only getting called once, it prints the output twice.I've read here (https://stackoverflow.com/questions/54957409/why-does-the-console-log-appear-twice-in-app-js-in-nodejs) that as I am using Chrome, it must be because of a pre-flight CORS - you're doing one request but the browser is doing two so it shows both. Is anyone able to explain what this means exactly and why it happens in Chrome but not Firefox (in Firefox, it only prints once)? I'm on port 3000 - I've read the StackOverflow post but don't really understand why making the request through a browser means you're doing it to a different port.Thank you- any help would be appreciated!

Submitted June 24, 2020 at 02:27PM by definitely-trying

[Ask] Should You Centralize Error Handling?

I was wondering about this, and forgive me if I misunderstood it, but there seems to be a difference in opinion on handling errors.My question is:Should both operational and programmer errors be handled in a centralized place?References:Against Central Error Handling (or at least I interpreted it that way)Handling operational errorsJust like performance and security, error handling isn’t something that can be bolted onto a program that has no error handling already. Nor can you centralize all error handling in one part of the program, the same way you can’t centralize “performance” in one part of the program. Any code that does anything which might possibly fail (opening a file, connecting to a server, forking a child process, and so on) has to consider what happens when that operation fails. That includes knowing how it may fail (the failure mode) and what such a failure would indicate. More on this later, but the key point here is that error handling has to be done in a fine-grained way because the impact and response depend on exactly what failed and why.You may end up handling the same error at several levels of the stack. This happens when lower levels can’t do anything useful except propagate the error to their caller, which propagates the error to its caller, and so on. Often, only the top-level caller knows what the appropriate response is, whether that’s to retry the operation, report an error to the user, or something else. But that doesn’t mean you should try to report all errors to a single top-level callback, because that callback itself can’t know in what context the error occurred, what pieces of an operation have successfully completed, and which ones actually failed.- https://www.joyent.com/node-js/production/design/errors​For Central Error Handling2.4 Handle errors centrally, not within an Express middlewareTL;DR: Error handling logic such as mail to admin and logging should be encapsulated in a dedicated and centralized object that all endpoints (e.g. Express middleware, cron jobs, unit-testing) call when an error comes inOtherwise: Not handling errors within a single place will lead to code duplication and probably to improperly handled errors- https://github.com/goldbergyoni/nodebestpractices#-24-handle-errors-centrally-not-within-an-express-middleware

Submitted June 24, 2020 at 01:26PM by codingwithmanny

Async Method Chaining in Node: A quick study on building a Promise Queue Pipeline

https://medium.com/@hgmaxwellking/async-method-chaining-in-node-8c24c8c3a28d

Submitted June 24, 2020 at 01:34PM by hghimself

npm install : unable to install all packages

Make your first image classifier using tensorflow.js and node.js

https://youtu.be/eoF__j3Tq28

Submitted June 24, 2020 at 10:10AM by adam0ling

GUID Query Through Mongo Shell

https://www.loginradius.com/engineering/blog/guid-query-mongo-shell/

Submitted June 24, 2020 at 07:44AM by aman_agrwl

Tuesday 23 June 2020

How do I structure this type of passport boilerplate code better, it looks very messy

https://i.redd.it/n4llmz3zks651.png

Submitted June 24, 2020 at 06:14AM by amazeguy

[Open-source] OpenRadio

I'm not sure if this is the right place to post projects so feel free to lock/delete this and point me in a good place to post this project.I've always wanted to make something like this but I was limited by the way python works. Streams weren't commonly used in python and the youtube-dl library doesn't support it plus it gets blocked a lot. Using ytdl-core with streams was a lot better. Anyway, without further ado lemme present my project OpenRadioHave you ever wanted to create your own music radio stations that cycle randomly or just cycle through songs in playlists? OpenRadio makes this possible without setting up a fully-fledged streaming server like icecast(I do recommend it if you are running something like a podcast). Each radio has it's own url and is a infinite mp3 file. To conserve resources radio stations check if users are listening at the end of each song and automatically shut down if they aren't and restart when they start listening again. Also since each station has it's own url you can listen to your radio from smart devices like google cast(Use https://speedtesting.herokuapp.com/cloudcast/ and input your url) and theoretically can play on amazon alexa. There is a simple admin interface available on /admin to manage your playlists without having to dig into a json or sqlite db. Also recently I added a visualizer using butterchurn which you can enable by typing "milkdrop" into the page.SetupAll you need to do is extract a release(recommended) or download the repo. Create a file called .env. This will be used to store the most sensitive information so keep this file safe. In this file put the followingSECRET=somethingrandom PASSWORD=adminpasswordhere PORT=portnumberhere To start the server run `node server.js`. I strongly recommend you have a https connection otherwise your password can be stolen pretty easily.Other Links + demoI have an instance running at: https://frill-corn.glitch.meIf no one is on for 5 mins it turns off automaticallyAlso if you are interested here's my original thread I made when I worked on this project: https://support.glitch.com/t/openradio-make-your-own-radio/25275/1Github: https://github.com/javaarchive/OpenRadio/blob/glitch/server.jsReleases: https://github.com/javaarchive/OpenRadio/releases

Submitted June 24, 2020 at 05:38AM by smashjarchivemaster

mutual-exclusion: Node.js library for handling mutual exclusion (mutex)

https://github.com/gajus/mutual-exclusion

Submitted June 24, 2020 at 04:28AM by gajus0

NPM not working since updating to WSL 2

I've updated to WSL 2 the other day.I reinstalled Ubuntu 18.04 .I previously used Ubuntu 18.04 on WSL 1 and all my dev environment was set on that one. I had node and npm on that.But after updating to WSL 2, I'm getting the following error when I'm typing npm$ npm -bash: /mnt/c/Program Files/nodejs/npm: /bin/sh^M: bad interpreter: No such file or directory $ node --version v8.10.0 $ npm --version -bash: /mnt/c/Program Files/nodejs/npm: /bin/shM: bad interpreter: No such file or directory I have nodejs installed through :sudo apt install nodejs I have also tried reinstalling nodejs, but that didn't help either.What can I do to solve this error?

Submitted June 24, 2020 at 04:15AM by BonSim

Best tools for dynamic file access (without Amazon S3)

I am designing a simple web application with Node as a web server. I am deploying this app in a VPS and each service is containerized via Docker. Other supplementary services the web server has are Nginx (for reverse proxy and static file access) and PostgreSQL (for storage of records).I'm trying to add a feature wherein users can change whether some static files can be read or not by other users. It's kind of a private storage wherein the those who access the web server will or will not be able to view those files based on their user privileges.My initial solution would be use the fs module to change the file permissions of certain static files to certain users. However, this requires switching to a different user in the VPS's OS who will be considered as the owner of the files. Using the fs module also means tight coupling with the OS and the file system making it hard to migrate to different storage solutions.Are there any services which that does this which can easily be containerized as a service? The reason I'm not using S3 yet is cost. There's a free tier for S3 but I don't want to use it yet until my VPS disk storage is used up.

Submitted June 24, 2020 at 03:51AM by CaptainMelancholic

webpack-bundle-tracker not creating webpack-stats.json?

/r/vuejs/comments/heoeh8/webpackbundletracker_not_creating_webpackstatsjson/

Submitted June 23, 2020 at 11:20PM by 123blobfish123

Can't figure out how to successfully connect to MS Sql Server database using mssql

I'm using the mssql npm package to connect to my school's remote ms sql server. I can successfully connect to the server in sql server management studio, but when I try doing so using node, it keeps saying "Failed to connect to SQL.NEIT.EDU\\STUDENTSQLSERVER,4500 in 15000ms". I can't figure out what I am doing wrong because i'm using the same info I use in sql server management studio, which does work.​Can connect successfully in sql server management studioThis is all of my codeThis is my error

Submitted June 23, 2020 at 09:31PM by DontWorryAboutIt00

Is there an approach guide to news page projects

Hi everyone! I am building a network of niche fansite pages collecting news and interviews. Data of these will further be used for one bigger news portal. In this project I will have to make my skills of things like cleverly managing a set of databases/one relatively big database gathering user data for sorting the most popular topics creating a very user friendly UI for users that will input data And much more. I was wondering if there are any guides that touch on such project planning and structuring that you could share.

Submitted June 23, 2020 at 08:59PM by Fukkuro

[Ask] What Is The Convention For Gracefully Restarting NodeJS In Docker?

If my NodeJS app constantly restarts, what service should I be using within Docker?pm2-runtime (https://pm2.keymetrics.io/docs/usage/docker-pm2-nodejs/)nodemon (don't really think this is the right solution)rely on Docker/Kubernetes to restart the containerOther​Bonus question, if anyone has implemented this before, would love to know the reason why they chose this convention/tool/way and if there are any drawbacks.​Following the convention from:The best way to recover from programmer errors is to crash immediately. You should run your programs using a restarter that will automatically restart the program in the event of a crash. With a restarter in place, crashing is the fastest way to restore reliable service in the face of a transient programmer error.- https://www.joyent.com/node-js/production/design/errors​Also assuming, in my main file that I would have something like the following:process.on('uncaughtException', (e) => { // Code + Logging Here process.exit(1); }); process.on('unhandledRejection', (e) => { // Code + Logging Here process.exit(1); });

Submitted June 23, 2020 at 09:12PM by codingwithmanny

Question about path parameters in Express

I'm new to Express and have a question about how best to approach path parameters. I've defined some paths that look like the following:/objects /objects/:objectId /objects/:objectId/:itemWithinAnObjectId However, it seems like when I make a request to something like/objects/42/1 the handlers for both/objects/:objectId /objects/:objectId/:itemWithinAnObjectId are run.How do I get it to match the longest path? Should I just define one path and use '?' to make objectId and itemId optional?

Submitted June 23, 2020 at 08:38PM by wait_recordscratch

Question about Web Scraping

I've been working with Node about 4 years now, so I decided to do a web scraping project, as I've never done that before with Node. So what I'm attempting to do is scrape some stock data from Yahoo Finance.​My current methodology is performing a `GET` on the page I need, and parse it with `cheerio`. When I went to the site (while the market is live), I noticed that the values are being updated real time.​So my question is, does anyone know if it's possible to load in the JS from their site with `cheerio`, then wrap it it some way where I can also be a client to the socket that is emitting updates for the values?​Thanks

Submitted June 23, 2020 at 06:25PM by imanuglyperson

[Suggestion needed] System design: Post / Comment datamodel

Hi all, I want some suggestions regarding datamodel of a project I'm working on. For simplicity, let's assume that we're building a social media platform. There is an user microservice, and a post microservice. Now in post or comment model, we'll obviously store the userId of the author. The question is, should we store the author name and profile picture url in the post or comment table itself? Advantage is, to load a post or to load 20 comments at a time, we can simply get all the data from the same microservice, and a single query to the same table (post or comment). Disadvantage is, whenever user changes name or profile picture, we'll have to update all the posts and comments the user has done in his lifetime, which is a really heavy operation. The second approach will be, as you might have guessed, to not store user details (name, profile picture) in the post or comment, and fetching them from user microservice whenever we get a request for the post. Advantage is we can gracefully handle user name or profile picture changes. Disadvantage is, we have to do at least an additional request to user microservice whenever client asks for a post, or wants to load 20 comments.Any suggestion which approach you'll recommend? If you have any other suggestion, please do share that as well.Thanks in advance!

Submitted June 23, 2020 at 06:40PM by arpanbag001

how do i make a simple random string picker?

for example, every time i start the code, it randomly chooses one of the words i had set it (maybe inside a string array) to say, like ["hi", "hello", "hey"].thx!

Submitted June 23, 2020 at 05:27PM by SufferMyWrathBoi

How to import Excel sheet with cell width and color?

I've tried a few top libraries but if one supports cell width/color, it seems to be only in export.Open to anything that just gets that data. Thanks!

Submitted June 23, 2020 at 03:23PM by clarkmu

All you need to know about MongoDB schema migrations in node.js

https://softwareontheroad.com/database-migration-node-mongo/

Submitted June 23, 2020 at 03:11PM by santypk4

dotenv paths

// file tree src index.ts compiled index.js .env creds.json The index files have near the top require('dotenv').config()in .env I have this, but I'm not sure if the path resolution goes to the correct level. Any feedback appreciated: GOOGLE_APPLICATION_CREDENTIALS = "../googleCredentials.json";

Submitted June 23, 2020 at 01:24PM by fpuen

ID generator

Does anyone have any suggestions on how I can make an incrementing ID generator that will always be unique and 10 characters/digits long?

Submitted June 23, 2020 at 12:31PM by vVvswiftyvVv

My Node.js Project: The Schedulerctl Heroku Add-on

Hi everybody! Last week I vaguely introduced 2 Heroku add-ons that I am working on. Today I am putting 1 in the spotlight: https://schedulerctl.comSchedulerctl is built to enable you to automate, extend and combine Heroku Scheduler with other services through an ease-to-use and well-documented API. On top of that, you can create and manage your Heroku Scheduler jobs via the terminal by using the schedulerctl CLI.To be able to use Schedulerctl, Heroku Scheduler needs to be installed on the specific Heroku application. This way, both add-ons exists next to each other.This add-on is in the early stages of development and is almost ready to be tested in a closed environment. This is why I am actively looking for people who want to get early access and give Schedulerctl a try.Just provide your email through https://schedulerctl.com and I’ll get back to you!

Submitted June 23, 2020 at 12:38PM by OscarAvR

A CLI tool to scaffold your React components

https://github.com/iamtabrezkhan/awesome-react-generator

Submitted June 23, 2020 at 12:08PM by iamtabrezkhan

Angular, JavaScript, NodeJS, CSS, Html quick Concepts...

https://www.tutorialslogic.com/node-js?ver-latest.

Submitted June 23, 2020 at 10:59AM by ukmsoft

Does our data go through ISP servers during P2P network data transfers?

When we are connected in a P2P network (like WebRTC) does the data go from straight machine 1 to machine 2 or does it go through the ISP servers first.If it ges straight then doesn't that mean we can send unlimited amount of data without worrying about the data charges. Like can we send 10gb of data without spending any data from our ISP data plan.I was building a file transfer application with WebRTC and node so i thought of it. Is it true?

Submitted June 23, 2020 at 10:00AM by DeusExMachina24

How to create "smart" data structure for questionnaires?

I'm building a Node app where users can customize a more-or-less standardized questionnaire and send it to other people. The questionnaire functions like a flow-diagram. So if you e. g. answer "no" to question 2, question 3-10 will be skipped and the next question would be question 11.I'm not sure how to create and persist a good data structure for this. Do you guys are aware of any references? Is it the right approach to just stringify and object and save it to the database (I'm using Postgres)? Thanks.

Submitted June 23, 2020 at 09:35AM by memo_mar

List of tools you can use for checking vulnerabilities in Node.js

https://www.freecodecamp.org/news/6-tools-you-can-use-to-check-for-vulnerabilities-in-node-js/

Submitted June 23, 2020 at 07:38AM by jpham540

Monday 22 June 2020

What is cryptography, what can I use it for, where are some good sourced where I can learn all about hashing?

I'm familiar with the term "hash", encrypted data that resolves to decrypted data, I have been searching for tutorials online but most of them just give some code and don't really explain how everything works.if anyone can help me that would be cool.

Submitted June 23, 2020 at 04:18AM by BehindTheSpice

Humble Book Bundle: Technology Essentials for Business (pay what you want and help charity)

https://www.humblebundle.com/books/technology-essentials-for-business-manning-publications-books?partner=repsup

Submitted June 23, 2020 at 03:08AM by big_clips

Help understanding running multile servers in production.

So im a little confused how things work when i'm hosting on let's say Heroku.Here is my Github for this project which i am referencing.https://github.com/TarikGul/portfolio​So Im confused how multiple servers run at the same time and how Heroku detects it. So in my app.js express is listening on port 5000. In my package.json, i refer to my 'main' as app.js which i'm assuming runs the file and then the server is created and starts listening. But i also need to run a separate server on port 1337 for my webhook that is receiving messages from Twilio which is in routes/api/message_server.js.When im in development, i just run the file and it listens and im able to run tests etc. But in production how do i get that server up and running so i can listen on port 1337 as well as port 5000.Would I just import the app from message_server.js into app.js and listen from there?If there is anything else i can provide please let me know. Thanks again.

Submitted June 23, 2020 at 01:52AM by himurax3x

which one is easier to learn fastify or restify?

Hi, i am migrating from php to a rest framework using nodejs, i have read a lot about the myriad of frameworks available but i concluded i should go with fastify or restify, my main concern is which one is easier to learn, i am no interested in blazingly fast or anything like that, i am sure i can spare a few miliseconds, my company is not even close to fortune 500. Also i don't want to code 60% or more from scratch so express is not an option.I ask for your advise which one should i use, for example i know there is fastify-cli to bootstrap the application, there is not something similar for restify, in the other hand restify looks good enough and has pleny of plugins, i need to connect to remote apis and the included http client looks promising, in fastify most people recommend axios (a third party plugin), so in the end i am not very confident i wil take the best choice for my devel team. Kind regards.

Submitted June 23, 2020 at 12:22AM by miguelmirandag

First open source project. Monitor, notify, and update your containers.

https://www.npmjs.com/package/@jakowenko/watchtower

Submitted June 23, 2020 at 12:49AM by Jakowenko

Uploading image to Azure Blob Storage

Hi guys, I have a question regarding the upload of image. I am using azure-storage library for uploading. The question is, how can I get the location of the image that I have uploaded so that it will be stored in database for future?

Submitted June 22, 2020 at 06:47PM by WaitYouKnowMe

Resources to be an Intermediate Node.js developer

I got familiar with Node.js about a year ago and since then I have made simple apps mainly using Express.js and few bots on Twitter using bare Node.js but I feel that till now I have just scratched the surface as I have been working with simple JS stuff like promises, async-await, etc. And recently I discovered a great book by Flavio Copes and now I want to learn some intermediate/advanced stuff. So any heads-up would be really appreciated.

Submitted June 22, 2020 at 06:06PM by neer17

Angular, JavaScript, NodeJS, CSS, Html quick Concepts...

https://www.tutorialslogic.com/node-js?ver.latest.

Submitted June 22, 2020 at 06:11PM by ukmsoft

Syncronize callback

Hi, i want to syncronize a callback, how is the best ways to do it.here is my code:http://pastie.org/p/3VEVgZaN630SKHquyzAnnLi need to syncronize the callback(toBuffer) with the function htmlToPdfraw code :function htmlToPdf(html){let options = { format: 'A4',base:'file://' + __dirname + '../public/'  };let resultado = null;pdf.create(html,options).toBuffer((err,buffer)=>{if(!err){resultado = buffer;console.log(resultado)    }  })return resultado}

Submitted June 22, 2020 at 05:36PM by walace47