Friday 31 July 2020

Made a template to help NodeJs developers spin up a production-ready server ready to code!

It's been almost 4years since I have been writing nodejs, it's been really cool, but at times - when starting a new project - I need to do the same things again and again, for example, adding eslint, prettier, GitHub, swagger, and mocha - All these are now sort of necessary for an app.So I simplified it for myself (and for you - it's public), I have created a nodejs API template on Github you can use it to create a ready to code like environment.Features:Express app optimized to make better APIsChanged structure to fit the API only use caseRemoved view and public folderAdded error handling without HTML/templating enginesAdded test route to understand the file structure and code splittingDatabase connection using mongoose, based on environment (production-ready)Environment variable to help you control the app environment using dotenvSwagger for API documentationPre-configured husky to run eslint and prettier on the pre-commit hook, helps maintain best practicesAutomatic versioning for apps on git push, using yarnTests pre-configured using mocha and chaiHere are things you can do:

Submitted August 01, 2020 at 07:04AM by raj_chandra3

Need help in node.js

I started my web development journey last month. I know basics of CSS and Bootstrap 4 and started JavaScript too. I want to start backend too.Any one who just started learning node.js??Can you teach me? This way you will get practice on node and i will learn it too. Please can you teach me or anyone who can help me.Thanks

Submitted August 01, 2020 at 05:44AM by rghvprince

configuring TypeScript finally made easy...

https://www.stackchief.com/blog/tsconfig%20%7C%20the%20missing%20docs

Submitted August 01, 2020 at 05:27AM by stackchief

Swagger API

How to implement swagger API implementation for Node js webapi?

Submitted August 01, 2020 at 03:38AM by santech22

I’ve created a small lib to pick a random frame from an animated gif

https://github.com/jeffersonlicet/random-gif-split

Submitted August 01, 2020 at 01:23AM by jeffersonlicet

Help with Node app idea

Hello fellows Node developers. I come here to day in search of advice on an idea that I have for a web app but I'm not sure how to tackle it.I want to create a server that takes a video, process it probably with machine learning to blur the faces that appear in it, and then store it somewhere.The part that I'm unsure of is what technology can I use to blur the faces of the video. I've read that OpenCV has some libraries for that, but I don't know yet how to implement it. I'm also not sure whether to use python to process the video but tackle the requests and everything with node (don't even know if this is possible, calling a python script from node) or to use the tensorflow library for node.I hope you can shed some light on the subject, any help will be very appreciated!

Submitted July 31, 2020 at 09:27PM by JuanPablopiano

"Paypal, Netflix moved to Node from Java". Do they really rewrite the whole backend services on nodejs?

There have been so many articles on nodejs stating that this some big company uses node. But using as bff is one thing and using as primary backend language is another. So I have been curious about this topic a lot.Could anyone please clarify that.

Submitted July 31, 2020 at 07:43PM by nomikz

A node project idea for portfolio

I am a student and a full stack js dev, just looking for a good project idea to show off in my portfolio... It may be a clone or some other useful stuff... Please suggest some good stuff 🍬

Submitted July 31, 2020 at 07:35PM by kr-ujjwal

FREE Udemy Git & GitHub Crash Course - Let’s GIT it on Git Hub!

***Special Giveaway to Node Community:Enroll for FREE:https://www.udemy.com/course/git-and-github-crash-course/?couponCode=NODE_JULY***Hey r/node,My name is Vlad and I know that all of us, the developers, have to use some Version Control System during our development process. So I’ve decided to share with you guys my Crash Course that may help you to start working with Git & GitHub and use them for your own projects in just about 2 hours! :)Hopefully, you’ll find this content USEFUL!It’s GREAT for Beginners and for those who want to learn the topic once more in an easy, attractive, and summarized manner.The course covers:Introduction to VCS - What it is & Why you should use it ✔️Download & Install Git ✔️Creating First Git Project ✔️Basic Workflow of Git ✔️Reviewing Changes & Removing Files from Repo ✔️Introduction to GitHub! ✔️Exploring GitHub ✔️Creating a New Repository on GitHub ✔️Configuring SSH & Pushing Local to Remote ✔️Watch, Star, Raw, Blame, and History functionalities ✔️Issues & Labels ✔️“.gitignore” ✔️Fork, Clone, and Pull ✔️I would like to SHARE this course with you totally for FREE and hear your THOUGHTS & FEEDBACK on your Experience!***Get the course:Click here to enroll for FREE***Pay attention: This FREE Coupon expires in 3 days. Feel free to enroll & share it with any of your friends/juniors/students who might need it.Hope you will love it! ♥Enjoy! :)

Submitted July 31, 2020 at 05:21PM by JimLessly

Sequelize Express - update belongsToMany associations?

Hello,I'm new to the forum, and in process of learning Sequelize :)I'm stuck with trying to update two models with belongsToMany association..For instance lets say I have User and Projects.I know that when you make the association, it creates these 'magic functions' like 'addProject', and 'setProject'. But how do you 'updateProject'?For instance, if I want to update the projects assigned to a user, then I would do user.addProjects(projectId).But lets say I want to update a user's project with an array of projects.Something like: user.updateProjects(['4','2','3']). How is that accomplished? Appreciate any input I could get.

Submitted July 31, 2020 at 04:54PM by giantqtipz

Framework(s) to build a websocket API with OAuth2

Hi!Recently, I'm in charge of developing a side-project which should be a semi-public event real-time API which connects to my main project. Whenever an action happens on that project, we need to send an event to all connected websockets instances, more or less like Discord bots do with their websockets gateway.But that shouldn't be a public API at all - and we would like to keep diferent scopes for different users. Let's say that an official application uses this API with all scopes, an unofficial application but authorized from us shouldn't use all scopes but only the one we provide them, so basically we need OAuth2.Now, the problem is I never implemented an OAuth2 REST server; neither a websocket one. I only used it as a client. So I'd like a framework or a library which gets my work done easier, helping me learning to implement OAuth2.Also, I need a framework to which you can connect, well, module-agnostic, without using a custom built client. For example, I used socket.io some time ago for some private projects, and as I remember, you can't connect to socket.io directly without a socket.io client; you can't connect using browser's Websocket object. I need this because I don't know who my client may be and I can't force him to use specific clients.Also it'd be cool to develop in TypeScript, but that's a secondary thing for learning purposes.I tried the ws npm module, but seems harder than it should be to get things done just because I should implement OAuth2 from scratch.I tried Actionhero and it seems overkill for the project, to learn an entire new paradigm for something little as a small semi-public API with whitelisted access.I also tried Feather, but it seems to need a Feather client, or a socket.io client, and so it isn't module-agnostic.Thanks in advance for any help.

Submitted July 31, 2020 at 04:46PM by DanielVip3

How to resolve imports in Typescript Mocha Testing?

I'm having an issue importing various classes for mocha testing, for my Typescript project. I have included the following stackoverflow post for reference:https://stackoverflow.com/questions/63192719/how-to-resolve-class-is-not-a-constructor-error-in-typescript-mocha-testingnpm start works just fine but npm test is throwing an error where [Class] is not a constructor for most classes in my project.

Submitted July 31, 2020 at 04:04PM by e_n_v

Hope my post helps someone tackling the issue of solving problems

How do i learn or start something new

Submitted July 31, 2020 at 03:33PM by kr-ujjwal

How do I go about creating a docker file?

I need to create a Docker file for a web app which uses node.js, express.js, react, redux etc.Can someone point me a tutorial about how to create a Docker file so that I can dockerize it in a container and put it in a /xyz directory? Also, I am not sure if I need a start shell script something like that. The container will be used to deploy to the AWS ec2.I have problem in deciding what is the base file. Should it be node.js follows by the version?And also the cmd part ?Also, I want it like the Docker tutorial example once I run the image I can see the result in my browser.Thanks I’m advance for your help. Tks.

Submitted July 31, 2020 at 03:16PM by tangara888

Social Media Followers API (?)

Our company is looking for an API to get the number of social media followers a user has.We've looked into donReach Social API. However, it seems that API has been discontinued.Do you know of any other services that provide such a service?Any support is appreciated!

Submitted July 31, 2020 at 01:01PM by ineedhelpcoding

How to check security?

Hey, i started to learn javascript,Nodejs Html/css 4 months ago. Right now i can build my completly own website with a Own Login-System a forum or any common server sided code. In my opinion my code should be safe from SQL-injections or the cookie thing xms attacks or whatever it was called!My question:I´d like to check for security lacks. What would you recommend me to check what secuirty issues my server might have that i dont even know about?.​(as i said: as far as i understood nodejs/express, my Webpage should be safe but that doesnt mean that it actually is safe) I hope i could explain my problem!​sorry for grammar!​edit1: How should i find those security issues?

Submitted July 31, 2020 at 01:12PM by Cebrail_h

Why do we need to install nodemon and express?

I just started learning node js and I don’t really understand why do we need nodemon when we can easily do browser-sync and have it automatically update the web page for us and we will also have a localhost directly when we open it in a browser. Am I missing something?

Submitted July 31, 2020 at 12:21PM by funzimes

Node js api with swagger implementation

/r/Angular2/comments/i15bw9/node_js_api_with_swagger_implementation/

Submitted July 31, 2020 at 11:40AM by santech22

Why MVP Development Should Be Outsourced

http://selleo-mvp-development.icu

Submitted July 31, 2020 at 11:47AM by armabotwe

a chrome remote interface question..

i am an old school c language programmer, but i have recently taken an interest in doing some web programming, so i have done a tiny bit of homework about node(which i do enjoy), but i would like to figure out how to communicate with the devtools on the most low level way possible..i am probably headed in the wrong direction, but i am curious if someone could perhaps point me to a better subreddit to ask about this?for example, there is this file:https://source.chromium.org/chromium/chromium/src/+/master:native_client/tests/imc_sockets/socket_transfer_test.cnear the top of that file, i see this line:include "native_client/src/public/imc_syscalls.h"from where do i get this "native_client" include file from?i suppose that in a nutshell i would like to do what the node module "chrome-remote-interface" is doing, and so i am just starting this journey..my preferred programming language is c language.thank you.

Submitted July 31, 2020 at 11:56AM by smoknfx

Lightweight API validation using bueno

https://github.com/philipnilsson/bueno/blob/master/src/docs/lightweight-api.md#lightweight-api-validation-using-bueno

Submitted July 31, 2020 at 11:13AM by ueberbobo

Using websocket ( ws ) with live data streaming

let count = 1const progressbar = setInterval(() => {count = count + 1}, 1000);I have a simple interval as you can see above and I like to use this as feed for websocket.in my websocket script I havewss.on('connection' ,  ws => {console.log('user is connected to the server') ws.send(count)    })Now the count is send and received on the client side but it comes back as 1. I wish for the data to be sent on the interval and I was thinking if it is wise to put the whole websocket inside the interval or not.​Please guide me

Submitted July 31, 2020 at 10:57AM by godandglory2

Switching from java to node - what things should i learn/watch out for?

I've been a java/spring developer for almost 15 years, and although i can do some fullstack stuff i am more of a backend guy, and also more used to relational databases.This September i will be starting on a new fullstack job but as a javascript dev, the company uses the MERN stack. I've never touched nodejs code but i am hoping the experience and concepts/patterns i learned will help ease my transition.With regards to node and/or express.js, what things should i look to learn first? Or what gotchas should i watch out for given my java background? Thanks for all your advice.

Submitted July 31, 2020 at 08:55AM by borgy_t

Thursday 30 July 2020

Send data from server.js node to the client

Hi everyone, i bumped into a problem, i have a website in which i would like the user to be able to uploads files, then i would upload those files to google cloud storage and then i would download them so that the app.js script can fetch and get the file data from them. I already managed to sort out how to store the files in google cloud and download them, however i realized thet sending the files so that the app.js fetch them cannot be done , at least with the frameworks that i am working with. I am using multer, when i was storing the files locally on my machine everything worked fine since the fetch function was able to access to that folder, however when i deployed it, i also learned that you cannot upload or at least you have no idea of the heroku directory, hence i cant upload there, also for security reasons. I have been trying to wrap my head around this problem and come up with solutions that dont involve install a new dependency or learn a new framework, i want to be done with it and move on. I thought about handling the file data on the server side and then importing the modules but i cannot do that since the server serves the js file as a text/html mime type. The directory looks like this:-main -server.js-complement.js( i thought about importing the module variable here first and then adding the src script to the html but i still get the mime type error).----public----app.js(Here the fetch of the file takes place, and where i wanted to import the variable from the server or the file)Hopefully i can get some guidance, thankss.PS: Im a bit burnt out btw, maybe later on ill come back and add more things

Submitted July 31, 2020 at 07:21AM by rogerpeke97

Custom home server

Recently, I have seen videos where people create their own home server using a PC to locate files and using node and express to create a server with which they can access from any device connected to the wifi. I want to do this using my PC as a server, but I also want to access my Android file system using my PC, how can I access a connected device on my wifi using node? Example, if I have multiple devices connected to my wfi router, I want to be able to access the file system of each device

Submitted July 31, 2020 at 05:12AM by candreslobor

swc-node, the fastest TypeScript/JavaScript compiler in NodeJS, without node-gyp and postinstall scripts

https://github.com/Brooooooklyn/swc-node

Submitted July 31, 2020 at 04:03AM by LongYinan

Nodejs with FrontEnd (HTML, CSS, Bootstrap)

Hey I am learning node from codewithmosh and He is teaching with postman app. Can somebody help me in any way that I could use node with my frontend?

Submitted July 31, 2020 at 04:05AM by GisGenius

Dealing with 3rd party integrations. Where to start?

Hi! So a bit of background of our challenge. We have a main website where people get to access some reading resources. We also have "mini" sites or services that needs to integrate to our new platform. We have decided to make an "integrator" in our main site so all 3rd party applications will have a standard way to integrate to our main site. This is my first time to deal with this kind of challenge and I have some rough ideas but I believe it's all over the place. Maybe you could guys help out? Give some ideas or techniques how you dealt with this kind of problem?We're using AdonisJS as our backend and VueJS for our frontend if that helps.

Submitted July 31, 2020 at 03:21AM by vanilla_lurker

if you enjoy coding you should come and join our amazing discord server where we learn and have a fun time coding together.

https://discord.gg/wZQ2d7J

Submitted July 30, 2020 at 06:17PM by minazak1

Test Node with Docker, docker-compose and Postgres #4

https://www.youtube.com/watch?v=6gXRfUPAPl8

Submitted July 30, 2020 at 05:54PM by prodcoder

Learning path after REST API

Hi guys, I've been learning Nodejs for a while and have created several REST API with Express/GraphQL and MongoDB in the MVC model. I feel pretty comfortable with it but I don't really know what to learn next to become job-ready for a Backend NodeJS developer? Any suggestion is appreciated (please be as detail as possible)

Submitted July 30, 2020 at 05:29PM by hizen2501

Looking for NodeJS hosting recommendations (alternative to Heroku)

I am currently hosting all my Node applications using Heroku. I actually like the simplicity of it but I am missing one critical feature. I can not fire up multiple environments, like a Staging environment or a Testing environment.Does anybody have some good Node hosting recommendations? Auto deploying from Github is a must have.

Submitted July 30, 2020 at 02:51PM by chrisblackwell

Why does MongoDB get so much hate? (Genuine question)

Recently I have completed my MongoDB Developer Associate Certification. I also have experience using SQL Databases like MySQL and PostgreSQL. My experience in SQL is definitely a lot worse than my experience in MongoDB but I still think it should be enough for me to understand the differences between them and that I would be able to compare them in a good way. But still, when browsing this sub I see a lot of people complaining about MongoDB and saying that SQL is superior. I read these comments and try to be objective but I still find that I disagree with most of the stuff being said, even though those comments get a lot of upvotes, this makes me feel like I don't understand why it is bad or bad in certain situations. Please help me see, I want to learn!In this comment for example. I know it is kind of a meme but it still gets a lot of upvotes and I know there are a lot of people who genuinely believe that MongoDB is useless for every single use case and is basically unusable in production.Also, a lot of people say the performance of SQL databases can never be matched by databases like MongoDB but I find that not to be true. I have been googling around for a bit but can't find any nice recent performance comparisons. I can remember some benchmarks on StackOverflow that were showing that MongoDB was a few ms off compared to some SQL queries. But MongoDB offers you a lot, I find that my schemas are less complicated which also saves development cost due to reduced application complexity.There are a lot of people who say stuff like:A non-relation database? What!! Almost every schema needs relationships, what a dumb idea this can never work.This does not make any sense of course MongoDB supports relationships, it would indeed be pretty useless if it didn't. The very fact that the type "array" exists in MongoDB means that it has relations. An array. by itself basically means a one to many relationship. Also, there is support for joins ($lookup) and that kind of stuff so MongoDB clearly supports relationships. I have also seen that people say that joins in MongoDB (or $lookup) is slower than in SQL. Like I have stated above, I can't really find a good and recent performance comparison benchmark. If you do feel free to comment a link to it and I will try to update this post. But let's say theoretically that a $lookup is twice as slow as a SQL join. That would be a very large difference in a large scale project. I have had SQL projects that were around 7 to 10 tables in SQL but that could be reduced to 2 or 3 tables (collections) in MongoDB through the use of the array type. In that same schema, we sometimes had to join 5 different tables together and using MongoDB that could mostly be reduced to 0 joins ($lookup). So even if theoretically, MongoDB joins ($lookup) would be twice as slow it would have still been faster because you have to do a lot fewer joins in MongoDB compared to SQL.Also, a lot of people complain about MongoDB not supporting ACID. But MongoDB actually does support ACID through transactions.I am not an expert in any of this and I am not saying that everything I have mentioned above is correct, the opposite is true. I want to know why I am wrong please tell me and let's have a civil discussion! Sorry for being all over the place in my post. Also if I find some good comments I will try to add them to the post also if they are reasons against MongoDB (of course).

Submitted July 30, 2020 at 01:34PM by Wojtek1942

Using PassThrough Streams for Uploading to S3

https://medium.com/@mwillbanks/using-passthrough-streams-for-uploading-to-s3-c21c017af622

Submitted July 30, 2020 at 01:36PM by mwillbanks

How to install a specific node version

I'm trying to install a specific node version from https://nodejs.org/en/download/releases/ e.g I want to install Node.js 14.7.0 for windows which takes me to https://nodejs.org/download/release/v14.7.0/ and I'm unsure which one to click on from this list - I selected node-v14.7.0-win-x64.zip but didn't seem to install it properly - when I type node into my command prompt its undefined still, any suggestions?

Submitted July 30, 2020 at 12:55PM by J_S9991

How To Get Funding For An Online Marketplace Startup

http://selleo-funding.icu

Submitted July 30, 2020 at 11:57AM by sillycheetah59

Understanding Webhooks in Headless CMS

https://medium.com//understanding-webhooks-in-headless-cms-71e62fdf365b?source=friends_link&sk=2649f15746b596e5db73e601de84bfda

Submitted July 30, 2020 at 10:30AM by jsloverr

BSONRmgExp is not defined

How would you guys implement rate limitng without using libraries?

I've implemented one before using Postgres but now that I think of it, Redis is probably a better option. This is how I did itWhen a request is made, create a record with the URL endpoint, IP address, email address (for routes that requires user log in), last request at timestamp with current time, count at 1, and release at timestamp, say 1 minute from current timestampWhen subsequent request is made, retrieve the record, check the last request at timestamp with the request (current) timestamp.If it's 1 second apart, increase the count and update the last request at timestamp.If it's not, reset the count back to 1 and update the last request at timestamp.If the count reaches say, 10, check the timestamp of subsequent requests with the release at timstamp.If it's before, throw error. If after, process request and reset count back to 1 and update last request at timestamp.Should I rate limit all URL endpoints?Should all URL endpoints have the same window between requests?And should all URL endpoints have the same number of requests before reaching its limit and locking out subsequent requests?If you guys do it differently or have done it differently, please share.

Submitted July 30, 2020 at 10:54AM by eggtart_prince

is there any way to analyze SVG file in node?

Is there a alive version of local tunnel

Local tunnel doesn’t work anymore due to the servers being down I’ve tried alternatives but they either are paid or extremely limited with the free version I was wondering if there was a tool witch was free and I could have a static url (not one that changes every time I start the server)

Submitted July 30, 2020 at 10:19AM by RUGMJ7443

How to handle huge amount of data uploads?

Hello people.Im building a rest api backend using express.jsThere is a certain POST endpoint, that is taking gps data as the body. But when the gps data is huge, the application cannot handle it.What am I missing here? Any ideas how to solve this?

Submitted July 30, 2020 at 09:03AM by MonkeyDkon

Coming from PHP. What are the differences I should know to get started faster?

While I'm front-end oriented and is rather comfortable with web javascript, the only server-side language I can use for real work is PHP. So my understanding of how server-side works is rather limited to how PHP works on the machine. Regarding Node, I've only looked into a few videos and documents yet, but the way Node works seems to be much different than what I knew of PHP (i.e. PHP requires http server alongside in order to work, is it a correct understanding that Node does both http server and page scripting?)What are the core differences in terms of programming approach, practices and paradigms I should keep in mind, if I want to make less mistakes or dumb decisions?

Submitted July 30, 2020 at 08:36AM by hdd113

Algorithm for filtering products

I want to create the shopping site like myntra and I know how to make a normal filter but in myntra or lifestyle store they have categories,brand,type etc in filter menu if we click brand ex:Nike it will change entire data based on Nike on filter menu except that clicked categories one .. how it's work

Submitted July 30, 2020 at 08:12AM by mohamedimy

Mocking the Database in Unit Tests - WHY ?

Given that I'm fairly new to server side testing, I've read that you usually want to mock the db for unit tests, and my reaction is: why in the world would I ever want to do that ? Building a query for the db that actually works is a huge (if not the MAIN) part of the server side (especially in node, since it's not calculation heavy), and I make use of it in pretty much 95% of the requests probably.So why ? That would make tests pointless as they would just be testing that my mock responds well to queries (which doesn't make sense). What am I missing ?

Submitted July 30, 2020 at 08:10AM by Mautriz

CRUD app for Redis, ES, MongoDB, and Postgres

Hi, guys! To learn the language, I decided to make a crud application with a restful API. As I have free time I will add support for various databases. A project just for fun.https://github.com/ganochenkodg/svelte-crud

Submitted July 30, 2020 at 07:39AM by Dmitriy_Ganochenko

Wednesday 29 July 2020

What feature of NodeJs is used very often by experienced programmers, but not so much by a newbie?

Question inspiration from r/golanghttps://www.reddit.com/r/golang/comments/hp4mk3/what_feature_of_go_is_used_very_often_by/

Submitted July 30, 2020 at 06:07AM by Ncell50

Nodejs,Ruby on Rails,django

For a begginer what do recommend?View Poll

Submitted July 30, 2020 at 05:07AM by mohamedsayed2004

How to unit test private object variables mocha chai for typescript project?

After researching this I found the best response would be to test the private variables of an object against the prototype of the object. Effectively then inside the test creating a prototype and accessing the variables in that way. When I do this, however, it seems that all variables are not null but are undefined. How am I able to test the private variables, so that they remain defined? For reference, this is what I'm doing now:https://stackoverflow.com/questions/63162403/how-to-unit-test-private-variables-mocha-chai-for-typescript-project

Submitted July 29, 2020 at 10:11PM by e_n_v

Best way to sync dbs

I have a Magento db and postgres db for the app I am running. I want to sync data changes occuring in my Magento db for a particular table to be migarted to my postgres db each day.Wat I want to do is run a cron job every day and update postgres with latest increments changes.For that I want to use a AWS lambda to trigger a node js script which will use typeorm to connect to two dbs .it fetches from magento db in a single go and opens the postgres connection and writes to it.How should I modify this to be production quality? Is there a way to do it in batches or make it more reliable or fault tolerant or any good node js handling practices?PS: I dnt wanna use any queueus or messaging system

Submitted July 29, 2020 at 08:48PM by MardGreer93

How to resolve Error: error:0909006C:PEM routines:get_name:no start line ?

I have a Typescript project where I read in AmazonRootCA1.pem for fully functioning AwsIotRestApi. That is, when I run the API it seems to be working just fine. I want to test the API with mocha. When I attempt to do so I get the following error:Error: error:0909006C:PEM routines:get_name:no start line AmazonRootCA1.pem, the file which is being read is correctly formatted, so I'm not entirely sure how to go about solving this. Would anyone know how to resolve this error?

Submitted July 29, 2020 at 07:59PM by e_n_v

Node v14.7.0 (Current)

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

Submitted July 29, 2020 at 08:19PM by dwaxe

Koa or Express js resources

Hello, I'm looking for some good resources where I can learn how to do backend with Koa or ExpressJs. I'm mainly focused on front-end development with React but I have to do some fullstack with Shopify and I need a backend, so I would choose Koa or Express. If you know any good sources where I can learn about Auth, how to write a REST API, and stuff like that.Anything is good, thank you very much!

Submitted July 29, 2020 at 08:25PM by anakataidk

What all should one learn to become NodeJS developer?

Can I get a learning path or a road map?I've made some Rest APIs with Express and MongoDB. Couple of fullstack applications as well where I implemented User authentication using passport. What else do I need to learn to get a job as NodeJS dev?

Submitted July 29, 2020 at 07:36PM by azorahai7

Running yarn start hangs the terminal

Hi, I did some digging and couldn't find the answer, but is there a way to run yarn start without it hanging in the terminal (remote server)? My current solution is to just open up a new tab and then close the old one. Thanks in advance for this tiny blocker!

Submitted July 29, 2020 at 05:57PM by Kungfugrab

Integration through APIs

Beginner question here:I have 2 systems that I'm trying to integrate. I'll spare the details for now, but essentially I need to pull a quote from an accounting system into a CRM system. Both systems have quite an extensive API setup, so completely accessible from that perspective. I've used both APIs in the past, for other projects.My question is this:How do I get this to happen automatically? i.e the quote from the accounting system will be pulled into the CRM system automatically. I obviously do not have access to the code of either system as they are both big SaaS products. Just APIs...The idea is obviously to reduce the amount of work that a human being physically has to do, which is why I'm trying to automate as much as possible.My apologies if this is a dumb question, or if there is a simple fix - I've never been in this position before!

Submitted July 29, 2020 at 05:15PM by Bholz97

Scrapping an xml file and accessing its data elements

https://www.monkwhocode.com/2020/07/nodejs-downloading-xml-file-from-given.html

Submitted July 29, 2020 at 02:39PM by saurabhDvara

Snapshot testing

Snapshot testing is one of many different testing tools, which compares the previous and current snapshot. Unlike TDD, snapshot testing relies on the fact that your component renders correctly already.Component testing is the new trend, so how can you integrate this with nightwatch .Here is the linkhttps://www.loginradius.com/engineering/blog/snapshot-testing-using-nightwatch-and-mocha/

Submitted July 29, 2020 at 02:35PM by aman_agrwl

How do I mock an Azure SQL database using Jest?

Hi All,I am looking to mock an Azure SQL database for Unit testing purposes. My database does not have, nor will have, any triggers or procedures. Its all just simple select and join statements based on CRUD requests from my express endpoint. Is it possible for me to create a fake database file containing my schema and dummy data and intercept any requests from HTTP requests?Example code I want to test inside a Users route (ie. http://localhost:3000/users )​router.post('/', async (req, res) => { ...validator... try { const pool = await dbConnPoolPromise const result = await pool.request() .input('name', sql.NVarChar, validator.escape(req.body.name)) .input('role', sql.NVarChar, validator.escape(req.body.role)) .input('email', sql.NVarChar, validator.escape(req.body.email)) .query(SQL_INSERT); res.status(201); res.json(result.recordset[0]); } catch (err) { res.status(500); res.send("ERROR, Users Post" + err.message); } }); I would like to have a file that intercepts this POST request and immediately Promise resolve to, say:{recordset[{name:"Foo",role:"Bar",email:"foo@bar.com"}which shows the data that I have inserted.I can then do an assert based on this using Supertest. I have previously used Jest to mock functionality on the front end using the spyOn function so I imagine I can do something similar here but cannot find a lot of information on it. Has anyone done this before? Thanks!

Submitted July 29, 2020 at 01:09PM by rudeile

Best practices to limit timeouts when working with Slack API

Hi folks - I'm experiencing a ton of timeouts when working with the Slack API on my node server (currently I'm using serverless Google Cloud Functions). I'm wondering if there are any best practices I'm not using that are causing this slow downThe Slack API has a 3 second threshold before it assumes timeout or expires certain tokens. My functions aren't running that quickly. Specifically in my case, when a user uses a slack slash command, I want to send back a modal for them to fill out. However, the trigger_id that I need to send back with the modal is expiring before I can send itAny tips for a new user of both serverless and the Slack API? I posted more about it on StackOverflow as well

Submitted July 28, 2020 at 08:53PM by chums923

Send mongodb Object ID to the client

Hey,I am using mongodb for a project and I was wondering is it safe to expose the mongodb Object ID to the client side of application? Stackoverflow have some mixed answers. Should I use some module like uuid for generating random ids for the schema and send that instead? What are the industry practices regarding this issue? Thank you

Submitted July 29, 2020 at 09:37AM by __boomerang_

Create simple POS with React.js, Node.js, and MongoDB #10: CRUD Supplier

https://blog.soshace.com/create-simple-pos-with-react-js-node-js-and-mongodb-10-crud-supplier/

Submitted July 29, 2020 at 08:46AM by branikita

What is Node's way of doing something like PHP Sessions?

PHP Session come in handy in a lot of ways. Does Node have anything like this?

Submitted July 29, 2020 at 07:58AM by pigiou

trying to click a radio button using puppeteer, newbie here, how do i do this?

const puppeteer = require('puppeteer');(async function main() {try {const browser=await puppeteer.launch({headless: false}); const page=await browser.newPage(); page.setUserAgent('test browser');await page.goto('https://post.c.r.aigslist.org/c/hou');//i had to put a couple of dots in the url, apparently the dont allow cr.a.i.g.s.list posts here. //apparently automoderator doesnt like that url..console.log("loaded");await page.click('what goes here?')} catch (e) { console.log('our error',e);} })();

Submitted July 29, 2020 at 07:43AM by smoknfx

Tuesday 28 July 2020

About Assignment 4

I am stuck with post route , Did anyone progressed with assignment 4 for setting up favorites dish ?

Submitted July 29, 2020 at 04:02AM by abdi406

Discord.JS Unknown Command Duplication Glitch

Hello,​I am currently working on some code for my Discord Bot, and was wondering if anyone could help. Right now, if I do an unknown command, the right thing will pop up, but when I do a valid command, it will show the unknown command prompt, and the valid command's prompt. My guess is I have code that I would like to use, but right now, it is space insensitive, meaning it will not react with spaces. If the command is one word, it will work perfectly fine, but if the command is two words, it will not react, and will make a duplication glitch. Below is my code.client.on("message", message => { if(!message.content.startsWith(PREFIX)) return; const unknowncommand = new Discord.MessageEmbed() .setColor('GREEN') .setTitle('SCOTT') .setDescription('You\'ve entered an unknown command. \nUse **!help** to see all available commands.') let validCommands = ["eat cookies", "eat ice cream", "eat choice", "eat candy", "eat lollipops", "eat fudge", "eat donuts", "eat gum"]; const args = message.content.split(" "); const command = args.shift(); const isValid = validCommands.includes(command); if(!isValid){ if(message.author.bot) return; return message.channel.send(unknowncommand), console.log(`[SCOTT] ${message.author.username} entered an unknown command in "${message.guild.name}".`); } }); I do not know if this is the right place to ask, because in Stack Overflow, the community was very rude and unhelpful, so I hope to get better responses here, and for someone to tell me what I am doing wrong! Thank you!

Submitted July 29, 2020 at 01:15AM by Rockstarsong

Learn Node.js - my free JavaScript book

https://learnnodejs.dev/

Submitted July 28, 2020 at 09:20PM by getaclue_1

Hosting Node

Anyone have experience hosting node app on A2? I hate deployment so much

Submitted July 28, 2020 at 06:34PM by Jusaa

Nodejs gRPC example with Typescript and Sequelize

Hello, I just write a gRPC example project in Nodejs and Typescript. Can you check the repo? If you have any suggestions or anything else, definitely I am ready to hear from you.https://github.com/mirajehossain/nodejs-grpc-example-typescript

Submitted July 28, 2020 at 05:58PM by mirajehossain

Thinking of switching to Node for all my current and future projects?

Hello r/node! I have a couple questions about NodeJS. I'm sorry if they might sound stupid but I've never touched front end web for a long time as I'm mainly an iOS and Python dev.I'm having trouble as an indie developer/entrepreneur maintaining knowledge in a couple programming languages, so I was thinking of moving over to JavaScript to I can crush the Front End and Back End with just one programming language. I'm currently using Python Django for my server.It's just very hard maintaining knowledge in the Front End (JavaScript) for my website, also iOS (Swift) & Python (Backend). I hope you see my worries here.Anyway I wanted to ask if Node JS was production ready? Can I make banking applications with Node and maybe some blockchain projects in the future? Is machine learning viable with node and javascript? I just want to make sure I can use JavaScript and Node JS for all my future projects so I don't have to hop around all these frameworks and tools like I do now.Thank you in advanced for anyone who takes the time to answer these questions!

Submitted July 28, 2020 at 04:54PM by Red3nzo

Best JavaScript Courses to Learn

https://medium.com/@devexpert/25-best-javascript-courses-to-learn-2020-caf08f019a4f

Submitted July 28, 2020 at 04:54PM by gamesbon

Working with the Slack API in Node.js

http://thecodebarbarian.com/working-with-the-slack-api-in-node-js.html

Submitted July 28, 2020 at 04:55PM by code_barbarian

New trial available for scheduling your Node.js tasks on Heroku with Advanced Scheduler

Hi there, happy to announce that the Advanced Scheduler Heroku Add-on has a new trial plan available. Feel free to check it out and let me know what you think!https://elements.heroku.com/addons/advanced-scheduler

Submitted July 28, 2020 at 04:15PM by OscarAvR

Guys how do you plan before creating any project or site?

i am creating a small photography site, i have completed my design stuff and i wanna know how you guys planned, which tools you used. Give me some advice or anything that i can improve my project please.i planned to use nodejs as server and nextjs as client.share your experience that can help me.Sorry for my bad english.

Submitted July 28, 2020 at 03:05PM by PrajwalCH

Guess a date's format

Hi everyone, just finished major work on a package which guesses a given date's format. I think it's in a usable state. I'll keep adding support for other formats on an ad-hoc basis going further. Here is the package.

Submitted July 28, 2020 at 03:24PM by fuziduzi

Playing sound on the server

I've got a small piece of software which allows me to sync my hue lights to sound. I'm in the process of porting it to raspberry pi (accessible through a web interface). The raspberry pi will be connected to a surround sound system and needs to be able to play music when I hit the button via the web interface.I'm currently using https://github.com/shime/play-sound to use the system's default audio player to play the sound directly from node on an API call but found this a bit limiting - I can only start or stop the sound, I would also like to loop, pause, fade etc.Does anyone have any experience in doing something like this?My backup idea was to run 2 webservers so I can use the HTML audio API and use a streaming socket to communicate between the two - this seems overcomplicated though.

Submitted July 28, 2020 at 02:32PM by dtsn

How to do firebase the .Net style using NodeJs

https://zvado.herokuapp.com/blog/details/tOTky7WDAD393D4AoDSE

Submitted July 28, 2020 at 02:46PM by draganov11

I'm building a 16-bit virtual machine in JavaScript, but it only has 64kb of addressable memory. In this episode the bank switching technique common in retro game consoles is implemented, giving it a super charge!

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

Submitted July 28, 2020 at 02:00PM by FrancisStokes

Why you should try GraphQL?

https://blog.graphqleditor.com/why-you-should-try-graphql/

Submitted July 28, 2020 at 11:55AM by oczekkk

Tutorial: How can I handle common checks across different endpoints in an Express application?

It’s quite common if you’re building an API which serves and manipulates private data that you’ll want to check that a client has authorization to access specific API endpoints. Express has a powerful feature which can help you achieve this (or any other kind of common check): middleware functions.https://simonplend.com/how-can-i-handle-common-checks-across-different-endpoints-in-an-express-application/This blog post will guide you through writing your own Express middleware functions to perform common checks in your application.

Submitted July 28, 2020 at 11:28AM by simonplend

Unable to get sendinblue, sendgrid or mailchimp to work with my node app

For sendgrid their website is really buggy and after signup doesn't let me log in, for mailchimp's mandrill they seem to require an active domain and I'm just learning. Finally for sendinblue their api key throws the errorError: Key Not Found In Database (failure, 401)I am trying to use nodemail with any mail provider which will work, can anybody suggest one which functions?

Submitted July 28, 2020 at 10:42AM by azt4er

Jwt and logout

Hello,Here is a very simple question :I'm trying to build a community based app with JWT authentication. If a user logout, should I destroy the token in the backend, or just remove it from the frontend ?Thx !

Submitted July 28, 2020 at 10:54AM by Frizzoux

Best way to run migrations on new NOT NULL columns with TypeORM?

I use TypeORM with Postgres in my NestJS project. I disabled the synchronisation mode and use Typeorm to generate migrations and then perform them. However, sometimes, I need to add a new column into my entity which has the NOT NULL property. When this happens, I cannot migrate my DB with already has some data due to NOT NULL constraint of the new column. I have to wipe my DB clean first, then do the migration.How can I perform my migrations in a fancier manner? Especially when this needs to be deployed to a production server with real data in the DB.Thanks!tl;dr:how do I migrate and seed data at the same time to prevent NOT NULL constraints?

Submitted July 28, 2020 at 10:57AM by recycled_bin

How do I make my node server run on my local network

I’m trying to make a WebSocket application where when I press a button on a html page on my iPhone it sends a WebSocket message to my laptop to turn on a led with Johnny five I’ve tried sending WebSocket messages to my ip and on the port it’s listening on but it doesn’t seem to do anything how can I do this?

Submitted July 28, 2020 at 09:02AM by RUGMJ7443

Monday 27 July 2020

Created a Nodejs CLI for calculating CGPA using Inquirer.js, cli-table and Rxjs(Repo link in comments)

​https://reddit.com/link/hz99j7/video/n3233uoxkjd51/player

Submitted July 28, 2020 at 07:03AM by D10S_1

How to find all occurrences in an array in a field in mongoose and nodejs?

I am working on a project where I have a chat between users. In my chat schema, I record the users who are a part of that chat.I want to add a profile for all of my users, however, the only thing inside of the profile is which chats they are a part of. Basically, what I want to do is when a user visits their profile page, I run through all of the chats to and see which chats contain that user. I then return JSON containing which chats they are in. I'm having difficulty with this however, particularly with how to go through all of the chats to find instances of the user. Currently, I'm doing this:const user = req.user.id; const chats = Chat.find(chat => chat.users.includes(user)); However, it is not working. What should I do instead. Additionally, below are my files for my Chat model, and my entire get profile method, to get the chats. Any help is appreciated!​Chat Model:const mongoose = require('mongoose'); const Schema = mongoose.Schema; const ChatSchema = new Schema({ title: { type: String, required: true }, password: { type: String, required: true }, creator: { type: Schema.Types.ObjectId, ref: 'user' }, users: [ { user: { type: Schema.Types.ObjectId, ref: 'user' } } ], code: { type: String, required: true }, posts: [ { text: { type: String, required: true }, title: { type: String, required: true }, date: { type: Date, default: Date.now } } ], date: { type: Date, default: Date.now } }); module.exports = Chat = mongoose.model('chat', ChatSchema); profile endpoint:router.get('/me', auth, async (req, res) => { try { const user = req.user.id; console.log(user); const chats = Chat.find(chat => chat.users.includes(user)); res.json(chats); } catch (err) { console.error(err.message); res.status(500).send('Server Error'); } });

Submitted July 28, 2020 at 02:08AM by dwight12345

Really confused as to what's going on with this async/await function.

It's a pretty simple that function that hashes a password.async function createPassword(password) { try { const hashedPassword = await bcrypt.hash(password, 11).then(data => data); console.log('Logged: ', hashedPassword); return hashedPassword; } catch (err) { console.log(err); } } console.log('Returned: ', createPassword('hello')); I am so confused as to why logging 'hashPassword' works but returning it doesn't. On top of that, why does the console.log execute last? Any help would be greatly appreciated.

Submitted July 28, 2020 at 01:28AM by Sweeterman3

Using Puppeteer to scrape roms from a site! come ask me question!

https://twitch.tv/jamie_337_nichols

Submitted July 28, 2020 at 12:46AM by jamie337nichols

Correct way to load javascript files in Nodejs

I am using ejs. I have a partials called header.ejs and footer.ejs.The footer page looks something like this: //My scripts ........This header and footer template is used in all of my pages like:home page:<% include ./partials/header.ejs %> // HOME CONTENT <% include ./partials/footer.ejs %>Buy items page:<% include ./partials/header.ejs %> // BUY ITEMS CONTENT <% include ./partials/footer.ejs %>and so on. The problem is that now I have about 15 pages and about 25 javascript files. All pages load all javascript files even when most of them only need 3-4 javascript files at max.​Is there a good way to load page specific javascript files?

Submitted July 28, 2020 at 12:56AM by sahilgreen

ReferenceError: primordials is not defined

I try to execute the gulpfile.js with the live server, but I keep getting this error on my command terminal: ReferenceError: primordials is not defined (Terminal's called Cmder)It seems like I should upgrade the versions of either node or gulp. What do you guys think ?

Submitted July 27, 2020 at 08:44PM by erenftw

Newbie to Node.js

Over time I have grown quite fond of the backend. Hence, I have learned Javascript and the basics of Node.Js. While learning Node, i have also picked up some basics of express, npm, and mongoDB. So here comes my question: Should I start making my own basic application with these things while learning express, npm, and mongoDB more in depth?(i have only learned them on the surface)I am a bit confused at the time so I do apologize if I sound out of place, and I appreciate any feedback. Thanks in advance

Submitted July 27, 2020 at 07:33PM by TheSilentKillerr

Alternative to Prisma for Postgresql

Prisma + Postgresql is the go-to solution for my apps. I find Prisma to be better documented and more easily usable than TypeORM or MikroORM.However, I had a particular feature that I needed for an app that isn't available on Prisma. Currently, it isn't possible to increase the value of a certain field by a certain value using update. I mean, there is no way to do this:update table set field = field + 10 where (some condition) without resorting to raw SQL.Is there any alternative that is comparable to Prisma? I use code-first approach, ie. I declare the models in the code and migrate them to the DB instead of designing the schema using SQL.

Submitted July 27, 2020 at 06:20PM by Mycroft2046

Is it ok practice to create tables if not exists on start of node app?

I am in the middle of developing node backend with mysql database.I often reset, drop, delete, modify my database, thus sometimes my node.js would get errors that will not appear in production.

Submitted July 27, 2020 at 05:44PM by angeal98

Simplemvc.js – A highly opinionated web back end framework

https://jeremyaboyd.com/post/simplemvc-js

Submitted July 27, 2020 at 05:11PM by pimterry

How to resolve process.on() unit test error?

I want to test a warning process for a Typescript project. The code that I'm trying to test is the following and the specific error that I'm getting is in the following StackOverflow post.https://stackoverflow.com/questions/63119397/how-to-resolve-process-on-test-typescript-mocha-testing-using-sinon-spyAny advice on this would be greatly appreciated!

Submitted July 27, 2020 at 05:26PM by e_n_v

Test Node with Docker, docker-compose and Postgres #3

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

Submitted July 27, 2020 at 05:28PM by prodcoder

Can you recommend me a maintained boilerplate of NodeJS, Express, MySQL, TypeScript, Docker?

It needs to have these:NodeJSExpressMySQLTypeScriptWith optional support for:Docker -- prod and development configs are fine, but I can set these up laterPGSQLiteIt also needs to have auth boilerplate with JWT -- `/ login`, `/register`, `/me`And if services are separated from the controllers, it'd be amazing. I tried a couple repos but there are issues I wasn't able to resolve, not sure how to go about it.

Submitted July 27, 2020 at 04:59PM by throwaway3593156

How do I add multiple schema types for a single field inside a model in mongoose?

I'm creating a project management app using React, Node and MongoDB.I have created a project model (using Mongoose) with the following properties:const projectSchema = new mongoose.Schema({name: String,tables: {type: [],default: taskSchema,},deadline: Date,dateOfCreation:{type:Date,default:Date.now}});By default the tables property will be of the taskSchema type which consists of following properties:const taskSchema = new mongoose.Schema({name:String,assignedTo: [String],status: {type:Number,default:0},dueDate: Date,filesAttached: [String]});As one can see inside the projectSchema, I have defined a property tables which by default is of taskSchema type.I want to provide the user to add another table of some other schemaType like schoolSchema, which has properties like: numberOfStudents, services, activities etc..How do I specify the tables property of the projectSchema to have an array of different schemaTypes?Because the tables property can consist of both schoolSchema and taskSchema.How can I add multiple properties to a single field?

Submitted July 27, 2020 at 04:51PM by Vivek_Singh_Bisht

I really wish that I could help someone out with my repository.

https://github.com/TheFoxWithAnElytra/DDOSable

Submitted July 27, 2020 at 03:36PM by TheFoxWithAnElytra

Nestjs / Objection - do I need to abstract database query away from services?

HelloCurrently, I am using objectionjs with nestjs. ObjectionJs model is injected in services and I am doing database querying stuff from my there.The project itself is very simple now, so this approach works well for me, but I don't know If I will have issues after more functionality. This is my first project on the backend side, so I am trying to learn doing things the right way.Is there better way, to move information related logic into another layer? Like Repository or model itself?I can declare static & instance methods in Objectionjs model and move information getting logic there. (Like finding item by email, find related items from another tables, etc...)I can create an injectable repository (an idea borrowed from Typeform), which will extend the model and add querying stuff there.

Submitted July 27, 2020 at 03:45PM by Lasha9

How to build filter search using node/express?

Hi​I'm trying to build a filtered search in Node using express. Essentially a user selects criteria in a form, and I return results. I'm building this as a JSON API.​I receive a url which contains various query params (eg http://localhost:7777/property/search?county=kildare&bedrooms=2),​and this calls the following function​ exports.searchProperty = async (req, res) => { const query = { county: req.query.county || { $exists: true }, town: req.query.town || { $exists: true }, bedrooms: { $gte: parseInt(req.query.minbed) || 1, $lte: parseInt(req.query.maxbed) || 10, }, bathrooms: { $gte: parseInt(req.query.minbath) || 1, $lte: parseInt(req.query.maxbath) || 10, }, price: { $gte: parseInt(req.query.minprice) || 0, $lte: parseInt(req.query.maxprice) || 10000000, }, floorArea: { $gte: parseInt(req.query.minfloorarea) || 0, $lte: parseInt(req.query.maxfloorarea) || 10000, }, type: req.query.type || { $exists: true }, features: { $in: [req.query.features] } || { $exists: true }, }; const property = await Property.find(query); res.json({ items: property.length, property, }); }; ​Is there a better way to handle this. ie structure, handle fallbacks, and validation/security.

Submitted July 27, 2020 at 12:56PM by Deviso

Send Email in Nodejs with Expressjs

https://schadokar.dev/posts/how-to-send-email-in-nodejs-with-expressjs/

Submitted July 27, 2020 at 11:32AM by schadokar

Any NodeJS examples of using Redis as a caching step in front of a SQL server

I am writing a large CRUD and want to start using Redis as a cache server to speed up the purely SQL (PostgreSQL) backend. Are there any code examples on GitHub of applications which models relate to two DB's. I want to have a look at how they structure the models? Is it easy to do raw or are there ORM handle this? What are some patterns to use?

Submitted July 27, 2020 at 11:23AM by alpha-201

How'd you use the mssql buffer made from a varbinary containing a file in hex?

Hello, I having BIG issues sending file from my server to my client. Here's is what I'm doing:- on client side, I send the file object that multer download.- upon downloading on the server side, I read the file in HEX with fs and store the buffer as varbinary in my database using mssql, then delete the temporary file.That part above is working.Then when I make a get request to get the file and use it on my web app (webviewer, user icon, etc), mssql returns me a buffer for the varbinary column. This is where I'm lost. I don't know how to reconstruct the file from that buffer. Here's what I attempted:- sending the file in different format (binary, utf 8, hex,...) as string and trying to rewrite it on the client side in a new buffer, from which I would create a blob- sending the buffer containing the file with the content-type header set to its mime-type, then using a ReadableStream to write the file into a blob​The best I got was a corrupted file displaying gibberish and nonsense... I desperately need help, I have lost days on that and I'm making 0 progress... I've been searching again and again but it's like no one ever did what I'm trying to do, so I'm picking from solutions to other problems but it didn't work too well for me so far...

Submitted July 27, 2020 at 10:52AM by ArutanSipdrae

How to get make an [object: object: object] so I can finally use fs.readFile...

So Im trying to get something like this in my json file​- edit:- Im trying to get the data object to go in my createID statement but I dont know how to make 3 objects that look like my json file in javascript, I looked through many forums and w3school but none show how to make [object: object: object], I tried doing:​playerArea data.[message.author.username] = {usedactivate: 0}​with no luck because its incorrect I dont know how to make this statement and I require help its been 2 days working on this small code of how to make [object: object: object] and Im really fusterated...A simple example of how to add data object to [message.author.username] would be gladly apprieciated.The issue im having is I need to get fs.readFile to read my data but I cannot call it to read [message.author.username] so I need to make a data object to hold the player usernames then call fs.readFile to read "data".Im trying to make javascript code that makes this:​​{ "data": { "♡Yuzi♡": { "usedactivate": 0 } "Cytonic": { "usedactivate": 0 } } }​From Something like this:​playerArea is the json file[message.author.username] is the username of playercreateID is empty {}​​if(playerArea[message.author.username] === undefined) {createID [message.author.username] = {registy: usedactivate: 0}​

Submitted July 27, 2020 at 10:21AM by Yuzi1221

Need Help Parsing 90k JSON files

I have an assignment to create a simple site that parses a huge dateset of clinicals trials and returns the authors with most papers on a specific disease using a specific drug. Below is the code that I used:async function searchFilesInDirectoryAsync(dir, disease, drug) { const files = await fsReaddir(dir); console.time('test'); var i = 1 ; for (file of files) { console.log(i + '/89133'); i++; var fileContent = await fsReadFile(path.join(__dirname, dir, file)); fileContent = JSON.parse(fileContent); const texts = fileContent["body_text"]; const reducer = (accumulator, currentValue) => accumulator + currentValue['text']; const text = texts.reduce(reducer); const regexDisease = new RegExp('\\b' + disease + '\\b', 'i'); const regexDrug = new RegExp('\\b' + drug + '\\b', 'i'); if (regexDisease.test(text) && regexDrug.test(text)) { console.log('Found') } else { console.log('Not Found'); } } console.timeEnd('test'); } The problem is that the above code takes around 26 minutes for 89k files, the 89k files amount to around 1.5 gb of JSON files.The only way I can think of to increase performance here is to not use the reduce method to glue all the texts of a paper together but instead to run a regex on each text.The body text in the JSON files contains an array of many texts that all together make up the whole body text. One of the problems is that with the above code my PC caps my disk usage to 100% so it's bound there. Different ideas I had:- Run lots of processes in parallel- Find a way to regex for drug and disease in the same time though I found that it's not possible- Have node js call a executable from another programming language that has better performance- Maybe somehow to load the whole 1.5 gb dataset in memory for quicker readsI haven't tried any of the above mentioned ideas since I though I may get some good advice here on how to handle this problem.Any help is appreciated and thanks in advance for any answers.EDIT:Also below is a breakdown of how much time each step takes:read - 6.039msJSONParse - 0.387msreduce - 0.027msregex - 0.158mstest - 7.381ms

Submitted July 27, 2020 at 10:01AM by kimonides9

Feedback welcome on a youtube developer video series that I am building

I am recording a video series for building services. The latest video is Koa and Postges: Building a server with connected to postges. I would love feedback so that I can make upcoming video even better.Thank you.

Submitted July 27, 2020 at 07:30AM by SnooDoughnuts455

Sunday 26 July 2020

Cannot use import outside a module, even though the import is within a module?

I'm attempting to learn Node and JavaScript for probably the fifth time, and I'm stuck on what I assume is a pretty basic error. When trying to use import instead of require() I get the following errors:import { app, shell, BrowserWindow, Menu, ipcMain } from "electron"; ^^^^^^ SyntaxError: Cannot use import statement outside a module and a little farther down:(node:13732) Warning: require() of ES modules is not supported. require() of E:\Code\scheduler\main.js from E:\Code\scheduler\node_modules\electron\dist\resources\default_app.asar\main.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules. Instead rename E:\Code\scheduler\main.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from E:\Code\scheduler\package.json. The "explanation" it gives seems a little contradictory given that I am using import instead of require, and it says that it's an ES module yet above it tells me it isn't.After researching for a bit, I updated from v12 LTS to v14.6.0 which allows support for ES modules, and I added "type": "module" to my package.json in the root of the project. From my understanding this will make every .js file within the folder tree act as an ES module. However, I still get the same error and I have no idea why. Does it have something to do with Electron not supporting the use of import, or is it something else? If it is Electron, am I able to use require just for it but use import for everything else, or is it all or nothing?Here is the relevant code from my main.js:import { app, shell, BrowserWindow, Menu, ipcMain } from "electron"; import { MainWindow } from "./src/js/mainWindow.js"; function startApp() { const mainWindow = new MainWindow(); ... and from mainWindow.js:import {BrowserWindow, Menu, app, shell } from 'electron'; export class MainWindow { #browserWindow; constructor() { ... the rest of my code works fine, the import statements are my only problem. Any help is greatly appreciated!

Submitted July 27, 2020 at 04:47AM by Nightfuse

Line number error does not show up when using MSSQL Node?

Trying to define a google sheets query based on substring of user input...

https://i.redd.it/3aayrxmyuad51.png

Submitted July 27, 2020 at 02:14AM by SaintsThemeMM

I built a dating website

I built a dating site aimed at helping you find people to go on game dates or have anime watch dates with. I learned a lot while building this site and there is still more I want to add/improve. I'm excited to hear what all your thoughts are on anything you would like to see, or any issues you run into!Check it out here

Submitted July 27, 2020 at 01:49AM by JarethRRader

Prevent API spamming while developing

Hello r/node! I'm a newbie to Nodejs who is currently developing an Instagram bot. My problem is that I often hit the API rate limit because of the bot logging out and on again when saving and restarting during development. There's probably an easy solution to this problem but I haven't found anything yet. Is there a way to load the function that I'm currently working on separately so I don't have to restart the whole script?Many thanksBtw I'm using VSCode.

Submitted July 27, 2020 at 12:53AM by IceDops

ElectroCRUD 2 | Built on Electron

https://garrylachman.github.io/ElectroCRUD/

Submitted July 26, 2020 at 11:31PM by code5code

Looking for collaborators

Hey there. r/node, I'm in the middle of trying to recreate Agar.io, and I've been banging my head for the past few days, just frustrated at the lack of problems and the monotony of it all. I really don't want to abandon the whole project, so I was thinking, if I would work with a team of people, there would be a lot more creative ideas and solutions, a new fresh feel to the project, and a sense of direction. If anyone is interested in collaborating, or knows who/where to ask, please let me know. Thanks, y'all are the best!

Submitted July 26, 2020 at 11:40PM by benjixinator

Is node.js steadily declining?

It seems that event loop hype is fading away.I've been thinking of node and golang a lot lately and it seems that node is not that good for server.It does well as bff. But anyways it is more close to front than data. And at cpu intensive tasks, it is slow.On top of that, it seems that there is not that many jobs. Small to medium sized businesses may very well choose python, php with their mature and stable frameworks. As for node.js, it is not that good. Yes, there is express and nest but they are still not first class choice.I like js a lot. But after researching a bit, that's what I think of node.js.

Submitted July 26, 2020 at 09:49PM by nomikz

Cannot send message with passportjs

Hi everyone, im having issues figuring out how to display a flash message on my index.ejs page.My project structure looks like this :-server.js-views- -index.ejsi can redirect the user succesfully when the user and password is correct, however when it is not , i want to display a message in the ejs index but i wasnt succesful at. Here is my server.js code:this is the passportjs part:passport.use(new LocalStrategy((username, password, cb) => { client.connect(); client.query('SELECT * FROM users where first_name = $1', [username], (err, result) => { console.log(result); if (err) { console.log(err); return cb(err); } if (result.rowCount === 1) { const first = result.rows[0]; bcrypt.compare(password, first.password, (err, res) => { console.log(first.password) if (res) { console.log("MAG") cb(null, { id: first.id, username: first.first_name }) } else { console.log("Incorrect password") cb(null, fa) } }) } if (result.rowCount === 0) { console.log("No user with that name") return cb(null, false, { message: 'No user with that name' }) } }) })) passport.serializeUser((user, done) => { done(null, user.id) }) passport.deserializeUser((id, done) => { client.query('SELECT id FROM users WHERE id = $1', [parseInt(id, 10)], (err, results) => { if (err) { console.log(err); return done(err) } done(null, results.rows[0]) }) }) ​app.use(flash()) app.use(session({ secret: process.env.SESSION, resave: false, saveUninitialized: false })) app.use(passport.initialize()) app.use(passport.session()) ​and here is where the page redirects when the username and pass is correct:app.post('/', passport.authenticate('local'), function (req, res) { res.render('index.ejs', { success: 'WELCOME' }); }); index.ejs html<% if (success != 'a'){ %>

<% success %>

<%} %>​tried adding a message there too and in return done from the local strategy but i cant seem to make it work, at this point im a little burnt out, thats why im asking for help. Thanksss and if i wasnt specific enough im sorry

Submitted July 26, 2020 at 09:54PM by rogerpeke97

Humble JavaScript Coding Bundle - pay what you want and help charity

https://www.humblebundle.com/software/javascript-web-development-software?partner=indiekings&charity=24629

Submitted July 26, 2020 at 09:20PM by G4M1NG

Prevent attack using user creation in REST API

I've been planning out a project for quite some time now, and I am trying to figure out this one security flaw. I'm going to be using node and express for the front end and react native for the front end. The application is going to be on mobile devices only. Requests are going to be sent from the mobile device to the server to get data from the database.While I was thinking about the layout of the project I noticed one thing that could cause problems. I see no clear way to verify that requests to the user creation route are real traffic coming from the app other than having a pre-shared secret code that is sent along with the request, and even then the pre-shared secret could be extracted by decompiling the application. I think that there is potential for abuse of this via scripts with cURL to create large quantities of users. Is there any other way to combat this other than the aforementioned pre-shared secret?

Submitted July 26, 2020 at 07:26PM by Oatttts

Node memory RSS continue allocations

Hello, I make some application and meet with continue RSS increase. I think that is my code but nodedump provide only heap memory with my object and I have only 16 MB of memory. Right now I have around 1.0 - 1.5 GB memory usage. How to understand reason of this RSS memory growing?​RSS memory growing

Submitted July 26, 2020 at 06:56PM by vit1251

Trying to use Google Sheets API with node.js

Using this tutorial:​https://developers.google.com/sheets/api/quickstart/nodejs​But I cant run the sample. It says Invalid Token was provided. But it never prompts to authorize the creation of one as the tutorial says. Any thoughts?

Submitted July 26, 2020 at 05:10PM by SaintsThemeMM

Typescript learning materials?

Hi there. I have been working as a Full stack dev for last 15 months, mostly using javascript on both frontend(ReactJS) and backend(NodeJS). Now I need to upgrade my skill-set with typescript. So far I've read documentation and watched some tutorials and I have good understanding of main features. What I need now are books, github projects, or some good tutorials where typescript is implemented with the node js. Thanks for the suggestions! :D

Submitted July 26, 2020 at 04:46PM by marcos351

How to optimise node CPU usage

I have a program thats responsible for mapping out every point between two 3d coordinates. its really process intensive (usually using up to 3gb ram and 20% CPU), the math that it does is actually very simple but it has to do alot of it (mapping out several million coordinates at times)Is there anyway to let node use 100% of the CPU and get the program done alot faster?

Submitted July 26, 2020 at 04:16PM by KCGD_r

How do I send a variable into a function?

I’m trying to make a script where if I get a twitch msg it flashes a led with Johnny five but I’m getting a bit confused how can I allow my function to read variables I’ve assigned values to above the function?

Submitted July 26, 2020 at 03:34PM by RUGMJ7443

How to use moment module to add hours?

Hi,What basically I am trying to achieve is that I have a time stored somewhere let's say 10:00 and I want to add some hours in it.What I tried :var time = moment("10:00", "HH:MM");time.add(5,'hours')But this does not work. I am not even sure if I am initializing it right or not. Can someone help here?

Submitted July 26, 2020 at 01:33PM by GhostFoxGod

I’m trying to use Johnny five with my arduino but I get an error saying cannot find module @serialport/bindings how can I fix this?

I’m using a chromebook with r/crouton witch is running Linux any help?

Submitted July 26, 2020 at 01:16PM by RUGMJ7443

Symbol lookup error after fresh installation of nodejs on linux.

I just installed nodejs and npm on majaro. After installing, running node or npm gives :Node : symbol lookup error: unrefined symbol: nghttp2_option_set_max_settings.running node --version or anything gives the same error.

Submitted July 26, 2020 at 09:38AM by scaryAstronaut

Copy files from Dev Machine to a Server by going through couple of jumpbox

Hey everyone, I want to automate a scenario I face while developing for a particular project. I need to deploy a web app for an internal project. What I currently have to do is,Build it locallyCopy to server AFrom there copy to Server BUse a script to Jump to Server BRepeat above steps to go to Destination Server.There copy it to a specific folderRestart the process.Based on certain conditions, there might be some conditional logic involved too.I want to automate this and add it to projects npm scripts. What would be the best way to achieve this using Node.js? I'm also open to other solutions, but would prefer doing it via Node.

Submitted July 26, 2020 at 08:31AM by quietwolf95

Is Node.js really single threaded?

https://www.distributedstack.dev/is-node-js-single-threaded/

Submitted July 26, 2020 at 08:37AM by santhosh1993

Saturday 25 July 2020

How to keep track uncompressed originals Images and compressed ones

I had build a chokidar program to watch for images in a folder and compress them and put in another folder. But it misses a few images per thousand images. If I restart the program it iterates from first. And this Idea seems a compute waste if my library of images increase. Is there any way in which I can keep track of compressed images and process only uncompressed ones?

Submitted July 26, 2020 at 05:10AM by ArunJRK

Is there a built-in file buffer mechanism in fs module?

(Please don't confuse it with the Buffer class)I have read the whole fs module page on NodeJS documentation. But I haven't found any mention about a way to specify a file buffer for it.For example:- In C/C++, you can use setbuf or setvbuf function;- In C#, the FileStream class has certain constructors that allow you to set the buffer size, the class itself sets 4KB as the default buffer size.So is there any equivalent in NodeJS world or I have to make my own?Please note that I aware about Stream, but my need is the ability to seek backward and forward arbitrarily in a file (with the help of fs-ext package).

Submitted July 26, 2020 at 05:17AM by MeigyokuThmn

Node code doesn’t run while in game

Hello everyone. I was playing a mmo game last night and had to train some of skills which required routinely pressing some buttons. Long story short I’ve found this amazing robot.js library for node and used it to write a macro in order to automate game skill training. Problem is when I run it normally it works. I can see it writing all the letter in text doc. But when I run it while in game, it does nothing. It doesn’t simulate buttons or whatever. Any idea why is this not working? Thanks. 🙏

Submitted July 26, 2020 at 05:22AM by daxdax89

[Mongoose] What's the best way to implement dynamic auto-labeling on document creation?

Say I have collection Cars. Every time I insert a new Car, I want it to be automatically labeled as "Car_${Cars.length}". Every time, I remove a Car from Cars, I want to label to be adjusted accordingly:Before removed:Car_1 Car_2 Car_3 <--- To be removed Car_4 Car_5 After:Car_1 Car_2 Car_3 Car_4 So after Car_3 has been removed, Car_4 and Car_5 label are readjusted accordingly.Now, what's the best way to implement this? I know I can loop through the collection and reassign the label but that doesn't seems like a good idea in term of performance

Submitted July 26, 2020 at 04:37AM by kumagaitaro

Where to keep access tokens when client is making API calls

I've been working on a express + react + react-router app that involves the spotfiy API, and I've set up the Authorization Code Flow and it works fine. Once I get the token however, I'm not sure where I should keep it to make additional calls to the API. This stackoverflow post (Link) suggests that I could keep it in localStorage since the client will be the one making the requests, but I feel like I've seen a lot of people suggest against storing things like the access token in easily accessible places like that. Any advice/suggestions would be greatly appreciated!

Submitted July 26, 2020 at 01:33AM by Granttank

Using async await in Nodejs mssql package

I am using `node-mssql` package and wanted to export a connection pool that I can call in various routes.database.jsconst sql = require('mssql/msnodesqlv8'); const keys = require('../config/keys'); const util = require('util') //Need this package for windows authentication require('msnodesqlv8'); let config; console.log(keys) if (keys.db.state.toLowerCase() == "dev") { config = { user: keys.db.dev_user, password: keys.db.dev_password, server: keys.db.dev_server, // You can use 'localhost\\instance' to connect to named instance database: keys.db.dev_database, // driver:'msnodesqlv8', pool: { max: 10, min: 5, idleTimeoutMillis: 30000 }, options: { encrypt: false, instanceName: keys.db.dev_instanceName, enableArithAbort: true }, // port:57909, enableArithAbort: false } } console.log(config) let pool = new sql.ConnectionPool(config).connect() .then(query => { return query }) .catch(e => console.error("Database Trouble! ", e)) module.exports = pool; In one of my routes:const pool=require('../middleware/database') async function queryDatabase(){ try{ let rows = await pool let result = await rows.query(`Select * from table1`) let result2 = await rows.query(`Select * from table2`) } catch(err){ console.log(err) } } My code is working just fine and I am getting the results. But I really want to be able to dolet result = await pool.query(`Select * from table1`) directly without the line :let rows = await pool but when I do that I get an error:pool.query is not a function.I cannot figure out what is going on.

Submitted July 26, 2020 at 12:15AM by sahilgreen

Different ES6 “import” behavior between ESM Loader and Webpack?

Hi! I’m currently building a 3D multiplayer web game where my frontend consists of ES6 modules bundled with Webpack+babel. My backend uses vanilla node with the experimental ES6 module compatibility.One of my modules is used by both the client and the server, as they both need a copy of the game.This module uses three.js, but the problem is that when I try to include three using import * as THREE from “three”, THREE.Vector3 is apparently undefined on my node server while it works properly on the client.On the other hand, when I try to include three.js using import THREE from “three”, the opposite happens. THREE.Vector3 is defined on the server properly, but on the client it is undefined...Why does this discrepancy occur and how can I make it so that my module can be used on both the client and my node backend?

Submitted July 25, 2020 at 10:16PM by santoso-sheep

Which is easier to load balance? GraphQL subscription or socket.io?

I have a chat app (web and mobile) which uses socket.io to update the frontend data.I'm gonna need very soon to expend its resources by doing a load balancing and I see two options to do it but I don't know which one is easier to implement:Add Redis to the picture (The only reason I don't want Redis is because it is far too complex to install on my localhost (windows) which will make development (and future development) far too annoying... (because I'm gonna have to develop either on a Linux machine which I don't have, or on a development server which I can't really afford right now)Replace sockets.io with GraphQL's subscriptions, but I need to know if it's a solution which is easier to implement rather than using redis..I'd love to get help from people who had the change to load balance GraphQL and tell me how easy or hard it is to do it?Thank you in advance for any answer / advice :)

Submitted July 25, 2020 at 09:01PM by s_trader

Need help creating my first npm package

Hi guys,I would like to create an npm package written in typescript and I have some questions. First of all, I don't know much about creating an npm package but I'm sure with some browsing that can be done. But what if I'd like to make the lib written in typescript to make it consumable by typescript projects?How do I make the types available? Do I need to make a build step copying the source ts files and the compiled js files into a dist|lib|build|etc folder?

Submitted July 25, 2020 at 06:01PM by Jim-Y

Microservice Design Guide

https://medium.com/platform-engineer/microservices-design-guide-eca0b799a7e8

Submitted July 25, 2020 at 06:12PM by aman_agrwl

How do you share personal util modules between your projects?

How do you go about sharing a personal package (version controlled) between your projects? In my situation I’m using ts (src) and dist (js). I believe I can put it on github but not sure if it’s versioned or easy to pull down (nomenclature), also I’m guessing it is possible to publish to npm publically and give no fucks that no one will benefit from the package. What’s the move?Thanks!

Submitted July 25, 2020 at 05:31PM by UpOnCloud9

Serverless Node.js Function Protected with Auth0 and React + Demo

https://github.com/fleetfn/examples/tree/master/api-auth-protected-with-auth0-react

Submitted July 25, 2020 at 05:32PM by matuzalemteles

Can someone add a delay to this code?

// Example: Adding Money To A Userif (message.content.toUpperCase() === `${prefix}BEG`) {money.updateBal(message.author.id, 5 /* Value */).then((i) => { // money.updateBal grabs the (userID, value) value being how much you want to add, and puts it into 'i'.message.channel.send(`**You got $5!**\n**New Balance:** ${i.money}`);})

Submitted July 25, 2020 at 04:52PM by DirtySmallEPIC

GraphQL first full-stack starter kit with Node, React. Powered by TypeScript

https://github.com/karanpratapsingh/fullstack-starterkit

Submitted July 25, 2020 at 01:55PM by vertigo_101

Is there anyway to protect the route without using auth?

For example i have a route '/delete' which delete all the data from DB and i don't want to implement any user authentication but that route should not be visible to any others except me. So i thought not visible that router to app. Is it safe to do that or it will visible any way ?

Submitted July 25, 2020 at 02:19PM by PrajwalCH

Hosting for web development?

I am working on my first React + Next.js + Postgres project, and I would like to host it somewhere where I can quickly publish it / update it through some very simple CI/CD without the headaches of maintaning backend (like you have to in AWS, for example).​I heard that DigitalOcean is cheap, but it takes a lot of time to manage backend on your own. Can you advice me something else that will work as a weekend-project-quick-and-easy-hosting?

Submitted July 25, 2020 at 01:37PM by ddjohn33

Unable to write image file

I have an express app and using a form which takes a file as input. So in the formdata I get file URL like C:/fakepath/demo.jpgI have a function which is used to write this file to files directory in my app. Function goes like this :saveFile : function (filePath, cb) {let fileName = Date.now();let outputPath = __dirname + "/files/"+fileName+".jpg";fs.writeFile(outputPath, filePath, function (err) {if (err) {return cb(err);} else {return cb(null, constants.HOST_URL + outputPath);}});}This actually writes the file but it is empty. I want to write that file as jpg. How do I do that?

Submitted July 25, 2020 at 12:58PM by GhostFoxGod

How to access file directly in express app?

I have a node app running on a server (say abc.com). On this I have a files folder in which I have some image files. Now when I try to access abc.com/logo.png it will give me error 404 because there is no route for it. Is there any way to achieve this without adding a new route.I triedapp.use(express.static(path.join(__dirname, 'files')));but it did not work.

Submitted July 25, 2020 at 01:04PM by GhostFoxGod

Run MERN stack on local server

I have created a web app using the MERN stack. I am looking to deploy it to a local server but all I can find online is how to deploy it to Heroku.Is this possible and what steps do I need to take to have this running locally.Thanks

Submitted July 25, 2020 at 12:33PM by Stangineer

Different ES6 “import” behavior between ESM Loader and Webpack?

Hi! I’m currently building a 3D multiplayer web game where my frontend consists of ES6 modules bundled with Webpack. My backend uses node with the experimental ES6 module compatibility.One of my modules is used by both the client and the server, as they both need a copy of the game.This module uses three.js, and the problem is that when I try to include three using import * as THREE from “three”, THREE is apparently undefined on my node server while it works properly on the client.On the other hand, when I try to include three.js using import THREE from “three”, the opposite happens. THREE is defined on the server properly, but on the client it is undefined...Why does this discrepancy occur and how can I make it so that my module can be used on both the client and my node backend?

Submitted July 25, 2020 at 12:18PM by santoso-sheep

What is the advantage of using babel with nodejs?

Also when to use webpack with nodejs

Submitted July 25, 2020 at 12:01PM by PrajwalCH

Ideas on apk hosting application or platform in nodejs. Need to start the project from scratch.

Hey Node-Community!I am currently planning to building a small Node.js Platform for hosting apk files where I want to give the user the chance to search for apks and display them as well. Users may also be able to upload their apks for testing by simple registration form.Ideas and sample projects are welcome.Thanks in anticipation!!

Submitted July 25, 2020 at 10:52AM by talhaehind

Child_Processes to run python code

Could anyone suggest a good resource where i could learn to implement machine learning models in a NodeJs site using chile_processes?

Submitted July 25, 2020 at 08:08AM by berlin_1710

Friday 24 July 2020

I recommend Umbler to anyone looking for NodeJS hosting

https://www.umbler.com/en/?a=9jv4d6vj

Submitted July 25, 2020 at 06:15AM by xpecex

Made a video discussing why I chose Heroku over DigitalOcean for my VENM (Vue, Express, Node, Mongo) web app. How did you guys go about choosing what to use?

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

Submitted July 25, 2020 at 02:49AM by TeluguGameboy

bit confused about backend database validation in Node JS. please recommend the easiest tutorial.

I'm learning backend development and finished a course from Udemy. Since I've had a solid Javascript knowledge most of the part seemed easy to me. But not understanding the backend data validation part with MongoDB quite well. Is there any tutorial that describes it the best?

Submitted July 24, 2020 at 02:33PM by lastrumpet

Database Example

I am trying to find a good example of how a database should be handled in nodejs using mongodb.At the moment my DB calls are similar to this:function setCurrentDate(date){ return new Promise(function (resolve, reject) { try { MongoClient.connect(url, {useNewUrlParser: true}) .then((db) => { //Get the database let dbo = db.db('billboard'); let collection = dbo.collection('config'); collection.updateOne( { key: configKey}, {$set: { value: date }}, {upsert: true} ).then(() => { db.close().then(() => { resolve(true); }) }).catch((err) => { db.close().then(() => { reject(err); }); }); }); } catch (err) { reject(err); } }); } I am sure there are far better ways than calling the MongoClient.connect every single time and then adding all those closes manually. So I am looking to implement the DRY methodology but at the moment every single one of my DB methods starts with that MongoClient.connect and all of them have the db.close() littered through the call itself.I would greatly appreciate it if someone can point me in the right direction.

Submitted July 24, 2020 at 12:58PM by chamna312

Suggest me some MERN projects not advanced but simple and intermediate.

No text found

Submitted July 24, 2020 at 12:49PM by PrajwalCH

getting signup data using social-login package

as defined in the angularx-social-login we can get access to information such as name, email, photo URL, etc when a user wants to sign-in/signup into an app.but in facebook, there is an option for users to block other websites to get information, but in order for my web app to work, i need the user's email address or phone, so if there is some user who wants to login using facebook, but has disabled the sharing in fb,will the angularx-social-login package work if the fb/google does not provide email and all other details due to block from user..what logic to follow to get consistent data for my app, and i don't miss on this information..and also is there any such thing for google too???

Submitted July 24, 2020 at 10:56AM by meMindFlayer

Passportjs signup works in localhost but doesn't work after deploying in Heroku.

I'm using nodemailer to send a random code to the user and then redirecting them to a verify page where they paste the code to verify their account. I'm using mongo Altas.When I'm running it on localhost it works perfectly but when I deploy to my free version of Heroku the signup page redirects me to the same page as instructed to do for any errors.​Express-session middlewareapp.use(session({ secret: '9131848995', resave: false, saveUninitialized: false, store: new MongoStore({mongooseConnection: mongoose.connection}), cookie: { maxAge: 8 * 180 * 60 * 1000, } })); ​config/passport.jspassport.use('local.signup', new localStrategy({ usernameField: 'email', passwordField: 'password', passReqToCallback: true }, (req, email, password, done) => { req.checkBody('email', 'Invalid email').notEmpty().isEmail(); req.checkBody('password', 'Invalid password').notEmpty().isLength({min:6}); let errors = req.validationErrors(); if(errors){ let messages = []; errors.forEach((error)=>{ messages.push(error.msg); }); return done(null, false, req.flash('error', messages)) } User.findOne({'email': email}, (err, user)=> { if (err) { return done(err); } if (user) { return done(null, false, {message: 'Email is already in use.'}); } transporter.sendMail(Mail(email), (error, info)=>{ if(!error){ let newUser = new User(); newUser.email = email; newUser.password = newUser.encryptPassword(password); newUser.v_code = v_code; if (!err) { newUser.save((err, result)=>{ if (err) { return done(err); } return done(null, newUser); }); } } else { return done(null, false, {message: error}); } }); }) })); Signup routerouter.get('/signup', (req, res)=> { let messages = req.flash('error'); res.render('signup', {csrfToken: req.csrfToken(), messages: messages, hasError: messages.length > 0}); }); router.post('/signup', passport.authenticate('local.signup',{ successRedirect: '/user/verify', failureRedirect: '/user/signup', failureFlash: true })); ​Thank you <3.

Submitted July 24, 2020 at 10:25AM by sublimeDawn

How to parse an url that links to a zip file with zlib?

Hello,I have translations on the website lokalize, and a function that download them. In my response, I have the url of a zip file, that contains the json. So far so good.I need to extract the json from here, and then output it to a specific path. In order to do that, I use node's zlib.Here is my script:const updateTranslations = async (url, path) => { try { const response = await fetch(url) pipeline( fs.createReadStream(response.url), zlib.createGzip(), fs.createWriteStream(path) ); } catch (error) { throw new Error(error.message); } }; The error is:Error: ENOENT: no such file or directory, open 'https://s3-eu-west-1.amazonaws.com/lokalise-assets/files/export/blablabla.zip'The url is here, and when. I copy/paste it in my browser, the file downloads correctly. But zlib can't parse it, so the script crashes. How to fix this? Should I use another library? If so, which one?Thanks!

Submitted July 24, 2020 at 09:46AM by MonsieurLeland

Instagram-like recent searches

Hi, I'm trying to build an instagram clone for learning purposes, and now got kinda stuck on this recent searches feature.How would you go about implementing it?And if you have some good code examples please do share

Submitted July 24, 2020 at 08:54AM by venms

Is using ES6 modules in a node backend bad practice?

Hi! I’m currently building a multiplayer web game where my frontend consists of ES6 modules bundled with Webpack. I plan to use node for the backend.I’m thinking that I‘m going to have the server reuse some of the modules that are used on the frontend. The problem, however, is that Node doesn’t support ES6 imports!First of all, is it bad practice to make the server reuse client-side code? I thought it would be nice if the app was “isomorphic” so that I don’t have to rewrite code for my server’s copy of the game. But something doesn’t quite feel right about what I’m doing.Second of all, is it uncomventional/bad to also use Webpack+babel to bundle my backend? (so that I can use ES6 imports in my server?)

Submitted July 24, 2020 at 09:10AM by santoso-sheep

15 Essential Node.js Packages To Improve Developer Productivity

Node.js is a pioneer in the asynchronous framework markets and used to create quick and scalable network applications. It supports a huge pool of startups and businesses that earn hundreds of millions of dollars in revenue. Node.js is the greatest disclosure of modern server engineering that we use and is not showing any sign of stopping. A new release of Node.js secures some loopholes in OpenSSL, and supports languages like C and C++Node.js packages helps you to use an event-driven, non-blocking I/O model. These important features makes it efficient, lightweight and totally adept for data-intensive real-time applications. It helps in achieving many purposes like back-end, front-end, APIs and robotics, improvement of development workflow and work model.You can also know reasons of why Node.js has become a standard for enterprise web apps at- Why has Node.js become a standard for enterprise web apps?Significance of NPM-NPM is a JavaScript node package manager. It is a default method to manage packages in Node.js runtime environment and supports use cases like publish, discover, install and develop node programs. By using NPM, javascript developers can easily share the code that they have compose to solve specific issues and other developers can reuse this code for their application.Three specific components-WebsiteCommand Line Interface (CLI) known as the NPM clientRegistry (it is the directory of information about packages)Registry includes more than 1 million Node.js Packages. These packages help developers to code by bringing simplicity to work. They can just install many NPM packages, copy few snippets and get ready with a decent demo for a JIT presentation.Top 15 Node.js Packages To Improve Productivity-1. Browserify-This package allows developers to develop organised, systematic and easy to navigate client-side codebase. With the use of Browserify, you can develop components that assign dependencies according to their use in different conditions. Generally, Node.js projects have many Node.js Packages, libraries and scripts. At such cases this package helps you to organize and give proper structure.JavaScript libraries are complicated to manage and you have to continuously check the templates to analyse which script is used by which libraries. As soon as you go deep into a project, script increases and hence it becomes difficult to tab on libraries and widgets. 2. Express-One of the fastest ways to get a programming language to serve your needs is through a framework. Most of the common programming languages have similar structures. It is a widely used framework to create and publish applications, and APIs rapidly. This framework has a minimal structure and by using Express generator, you can immediately launch a functional application. Also you can combine it with other Node JS packages for better performance.3. Socket.io-It allows developers to build real-time communication applications that need real-time streams of content , either from data in working or through an API from an external source. For instance, an apps like Twitter bot to collect latest tweets, a Facebook bot to watch news and combinations of APIs that work with real-time data. 4. Mocha-Testing is necessary for any project because it shows the application’s  performance and the functioning of code. It is a Javascript framework that runs on browser and Node.js and also makes asynchronous testing easy. It runs sequentially with adaptable and accurate reporting.  Also it maps uncaught exceptions to the test cases. From the performance report, developers can find specific errors and find a solution for issues.5. Bower-These days, websites include external libraries, tools, JS related utilities, frameworks and hence it becomes complicated to keep track of all these. And here comes the significance of Bower. It is a great package manager to control such situations. It can manages all components like CSS, JS, HTML, fonts and visual content works also. Bower allocates all packages that you’re using and helps you to be updated and consistently checked against potential risks. 6. Karma-Testing is an essential part of your project as it maintains the stability and performance of application. Karma is an efficient testing tool that allows you to test the code in browser and cross-browser too. It is used for testing during local development, every file save and server integration. It works seamlessly with terminal too.7. JSHint-It is a linting tool that reviews your Javascript program and identifies mistakes and potential errors. When your codebase is large, possibility of errors also increase and hence requires more time for debugging. With this tool, developers can effectively detect issues in code that can be a leaking variable, syntax error or implicit type conversion that cause bugs. In short, this tool improves your code and saves time for debugging. 8. Gulp-With this node.js package, one can strengthen and automate  your application’s workflow and hence can increase your productivity in development workflow. It is easy to understand and implement and also offers a minimal API surface, major integrations that you can use with PHP, .NET, Node.js and Java.9. GraphicsMagick-ImageMagick and GraphicsMagick are the tools to manipulate visual content on the web. You can use both tools within your Node.js projects to optimize visual content. It’s documentation is easy to navigate and offers all tips and tricks, insights to use the GraphicsMagick library in a proper way.10. Restify-If you want to create a RESTful API, this library helps you with required tools to execute tasks. APIs are important in any node.js application as they make real-time more real. Restify is a helpful library for you while creating REST services for the web.11. Morgan-It is one of the most preferred library of Node developers. Morgan is a HTTP request logger that stores HTTP requests and give you appropriate insight into how your app is being used and where could be the potential errors might be that you haven’t explored.12. JOI-You can use this module for data validation process of your app. It could be easy scalar data types like strings and numbers or complicated values having multiple levels of objects and arrays. It is useful to build secure applications. 13. MongoDB Node.JS Driver-This library provides a necessary driver if you want to implement a full version of MongoDB within their Node.js projects. It provides a necessary space to use MongoDB to its node projects.14. Babel-Core-Babel-Core is a popular JavaScript transpiler having real name as 6to5. Initially it converts ES6 code to ES5 code but now it can convert ES6 to ES5, JSX to JavaScript, and Flow to JavaScript.15. Chalk-It is a very easy library that styles your terminal strings. Also the API of Chalk is simple and straightforward that works easily with all features of JavaScript that it offers natively.

Submitted July 24, 2020 at 08:03AM by SolaceInfotech

Google Cloud Functions finally support Node.js 12 (beta)

https://cloud.google.com/functions/docs/concepts/nodejs-runtime

Submitted July 24, 2020 at 08:22AM by davbeer

How am i suppossed to implement this? Selenium not allowed. I am using nodejs along with express.

https://i.redd.it/d5cdpwie2rc51.jpg

Submitted July 24, 2020 at 07:33AM by hj1509

Search by City and find closest matches

Hey Node-Community!I am currently building a small Node.js App where I have I want to give the user the chance to search by location (i.e. their city and/or street) and the app finds the closest items (think of Eventbrite where you can search for e.g. "New York Central Park" or "Brooklyn" and it outputs results matching that location).So I have app customers adding their items to the database and when they input their address it should be converted to geo coordinates and when a site visitor wants to search for e.g. "paris" it converts "paris" to geo coordinates and find all items that match a specific radius.Side note: I do have a little bit of Rails background, so if anyone is aware of the Geocoder gem — this is exactly what I want, but with/for node.Thank you!

Submitted July 24, 2020 at 07:31AM by thisisaloisson

Thursday 23 July 2020

Help needed with Promises and Async Await

Can somebody help me understand how do I move from callbacks to promises and async-await...I have read /watched a lot of tutorials but I am still able to understand it well... Although the callbacks do have a con of callback hell, I don't know, I somehow found it easy to read and understand... moreover, this transition of ES5 to ES6 is making me crazy... especially the fat arrow function :(

Submitted July 24, 2020 at 06:21AM by nikhilbhola

Please help me how to resolve npm ERR! missing script: start

Playing Audio to a specific output device

I have a project that where I am trying to play audio to a specific audio device using node and electron. The issue I am having is that I cannot seem to find a module that can list my output devices so I can select one then play audio on that device. Does anyone have any recommendations on how to do this or what modules I may be able to look at?

Submitted July 24, 2020 at 05:29AM by Fluffy-Thunder

How to increase code coverage for mocha testing on basic Typescript example

I want to get a better understanding of how to test these kinds of functions in Typescript using mocha. In the StackOverflow post below I've outlined a basic small Typescript file, which I want to test and increase code coverage. Right now I'm not sure why the breakdown of the testing is the way that it is (50% Stmts | 100% Branch | 0% Funcs | 50% Lines) and how I would be able to get everything to 100%.https://stackoverflow.com/questions/63065938/how-to-increase-code-coverage-for-mocha-testing-on-basic-typescript-exampleAny advice would greatly be appreciated!

Submitted July 24, 2020 at 03:47AM by e_n_v

Not so fast GraphQL...

https://www.stackchief.com/blog/What%20is%20GraphQL%3F

Submitted July 24, 2020 at 03:40AM by stackchief

I made a lightweight, easy file sharing/uploading service, thoughts?

With this project starting out like last year or so, I thought it would be a great idea to make it open source a few months later, and here it is Zipline - image/file uploading service & URL shortening service! Updated frequently with new features/bug fixses, it supports a multitude of databases, so you can get the correct fit, and last but not least its pretty configurable. Check it out, I'd love to get some feedback on this.

Submitted July 24, 2020 at 01:55AM by dicedtomato-real

Help with basic webserver with websocket

I am new to node.js, very new. I have done 1 other website that basically only had a single line of text. Nothing complicated. The project I am currently working on is a touch more complicated. I have a NAS that I would like to use to source photos for what is basically a digital picture frame. Getting the photos themselves is not that difficult, what is difficult however is that I would like to update the photos on the client without having to refresh the page. And from what I can tell using websockets seems to be the best option. The issue there is I dont know how to use it at all. My goal is that every day it picks a new folder and every minute or two it takes a new image and push it to the client.​The website design itself is super simple, just the image on a black background.Any suggestions would be greatly appriciated! I am also not opposed to changing from websockets or anything like that if it will be easier! It is also only going to be on the local network.​Thanks!

Submitted July 24, 2020 at 02:22AM by Bentrigger

How can i add a file browser to my web application?

I have device that is continually recording voice and stores it to a network drive. I was looking to be able to display this network drive with a nodejs web application. The files are stored in a .mp3 format and ideally id also like to be able to sort by date and play the files in the browser. How can I go about doing this

Submitted July 24, 2020 at 02:23AM by archhmod

How do i add a delay until you can use the command again?

// Example: Fetching Balanceif (message.content.toUpperCase() === `${prefix}BAL`) {money.fetchBal(message.author.id).then((i) => { // money.fetchBal grabs the userID, finds it, and puts it into 'i'.message.channel.send(`**Waifu Tokens:** ${i.money}`);})}

Submitted July 24, 2020 at 01:30AM by DirtySmallEPIC

Uploading GIFS to AMAZON S3, not working.

Hey devs!After several tutorials and questions found on SO, I came here for help. :PI have an API where I can send pictures to my bucket at S3. Everything is working fine, but when I upload a GIF, it doesn't work. The size is smaller than the original gif.I am using multer, aws-sdk, and multer-sharp-s3.Does anyone have any idea of what could be causing this? If I manually upload the same gif, it works!My code:const s3 = new aws.S3({ accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, }); const multerFilter = (req, file, cb) => { if (file.mimetype.startsWith("image")) { cb(null, true); } else { cb(new Error("Not an image! Please upload only an image."), false); } }; const upload = multer({ fileFilter: multerFilter, storage: multerSharp({ Key: (req, file, cb) => { const userId = `${req.user[0].login}`; const todaysDate = `-${Date.now().toString()}.`; const extension = file.mimetype.split("/")[1]; const finalStr = userId.concat(todaysDate, extension); const fullPath = "projects/" + userId + "/" + finalStr; cb(null, fullPath); }, s3, Bucket: process.env.AWS_BUCKET_NAME, ACL: "public-read", resize: { width: 1135, height: 715, }, }), }); Reading the docs for multer-sharp, they have a toFormat param, and they say that you can set up as "gif", but when I try, I got this error on my server:throw is.invalidParameterError('format', `one of: ${[...formats.keys()].join(', ')}`, format); ^ Error: Expected one of: heic, heif, jpeg, jpg, png, raw, tiff, webp for format but received gif of type string Thank you all!

Submitted July 24, 2020 at 01:38AM by lucasmrl