Sunday 31 May 2020

Ready to give Deno a try? Skip the boilerplate project set-up w/ this scaffolding template!

/r/Deno/comments/gueuwb/deno_scaffold_a_github_template_repo_with_best/

Submitted June 01, 2020 at 07:27AM by nocicept0r

Best practices for REST API design - Stack Overflow Blog

https://stackoverflow.blog/2020/03/02/best-practices-for-rest-api-design/

Submitted June 01, 2020 at 06:50AM by aman_agrwl

Do you know how to make Node.js application secure? Here are 24 best practices.

https://www.bacancytechnology.com/blog/24-best-practices-to-make-your-nodejs-application-secure

Submitted June 01, 2020 at 05:20AM by freelancerkatie

5 tips for beginners?

I’m new to node and I was wondering if there’s 5 quick tips or words of wisdom, anyone has for newbies?

Submitted June 01, 2020 at 04:12AM by aerovize

What's the point of an API immediately wrap DB (prisma, hasura etc)

I mean I have not dived into the docs of those things but they just automatically sounds like a bad idea to me. You have your application logic to write anyway right? Why would you want API to map to DB one to one?If you end up having to write custom logic anyway why not just write it on top of a DB like normally, it's not hard to make a graphql endpoint without these services.

Submitted June 01, 2020 at 03:52AM by nsonha

Free places to host a Twitter bot?

Ideally I could use Vercel--free, unlimited deployments. But it seems a bit janky. I can only figure out how to deploy the script as a Node API. The problem here is that I would need to deploy the script and then hit the endpoint example.now.sh/api/bot.js to actually run it, which is kind of janky.Is there an alternatives spot to deploy to that I should look at? Otherwise is there an elegant way to do this with Vercel?

Submitted June 01, 2020 at 01:39AM by HumanoidHumanOnEarth

Difference between res.send() and return res.send()? Are they the same?

Sorry if this question is obvious but I sometimes see one and sometimes see the other.Thanks :)

Submitted May 31, 2020 at 11:20PM by 0xcrypt0punk

What are the major reasons python is preferred over javascript (node.js) for heavy computations?

Hey everyone, first time posting on reddit so let me know if any rules are broken. So I've worked extensively with Nodejs and I understand where it absolutely shines (the reactor pattern enabled by libuv). Great choice for a backend with a lot of async I/O. What I don't clearly understand is why python is preferred for heavy computation jobs as it is also a high level language and from what I have seen it is slower than js(nodejs). Is it because of the libraries available in python for working with data?

Submitted May 31, 2020 at 10:45PM by tusharf5

Good uWebSockets.js documentation/examples for migrating from socket.io?

Hey all,Does anyone have any good resources for working with uWebSockets, especially from migrating from express + socket.io to just uWebSockets?After doing a lot of research it's clear that socket.io is slow and bloated while uws is the clear king in performance. I'm trying to switch over but a lot of the provided documentation seems shallow and too technical, I can't even find a document with all the app parameters I can pass. In comparison socket.io which to be fair is definitely more user friendly, has very clear documentation about every inch of the api and how to do every basic example you could want. The examples uws provides seem to be high level examples for niche production-ready cases.It's kinda surprising because it is VERY clear that the author of uws staunchly hates socket.io and how un-optimized it is, but provides nearly no 'user-friendly' documentation or tutorials about how to get the same functionality out of uws. Only thing about getting the same functionality I could find was one measly medium article that the package author wrote that helped a little, but it definitely isn't enough.Anything helps, I've really looked through youtube and the internet but I can barely find anything useful which is blowing my mind for a package that claims 50 mil + downloads.​Thanks!​edit: for example, I can find bits and pieces of the websocket portion of the package, but I can't even find how to serve a html file on request yet the docs claim the api is the same as express but .sendFile isn't a function.

Submitted May 31, 2020 at 10:13PM by DivineActions

Node.js 64-bit Hangs at "Installing 64-bit Python"

Has anyone encountered this? Is this something silly common to fix? I've been waiting for over an hour, and I'm fairly confident things are hanging. Python doesn't take that long to install. Lol

Submitted May 31, 2020 at 07:26PM by WASasquatch

Which database option should I choose?

So I'm trying to create an API using the MongoDB free tier resources and inserting/updating data I scrape daily.I've looked online for how to update all documents if their records already exist in my collection and I read that I would need to use a forEach loop and go over each record to see whether it needs to be updated or not. But isn't that very inefficient?Another (lazy) option I guess would be to drop the collection and re-upload the freshly scraped data (because that will have the most up-to-date values.)If we consider an SQL database by using the UPDATE query I could do this pretty easily (but isn't it the same as a for-each loop under the hood also) and not worry about storage too much because unlike MongoDB there are completely free database options.Also please correct me if I'm wrongThanks in advance : )

Submitted May 31, 2020 at 06:23PM by nebling

GCP cloud functions aren't allowing uploads to express API

Hi all, could you please assist. I have an express API wrapped in a GCP cloud function, I used the Serverless framework to manage my deployments to GCP. I have two endpoints currently, one is just a /helloWorld and the other an /uploadImage endpoint. I used Multer as my upload middleware.Both endpoints work fine locally, however, when I try to hit the API deployed to GCP cloud functions only the /helloWorld endpoints returns an expected response.The /upload endpoint returns a 500 with the message: "could not handle request" and what I gather from the logs is that, somehow, the image isn't being uploaded to GCP and the Multer middleware is basically receiving a null.I'm not sure where my issue is here. I have set all the requisites such as cors configs on the API.Any hints or guidance in this regard will be much appreciated.Thank you in advance. 🙏

Submitted May 31, 2020 at 05:39PM by EmoDiet

Real World Project Repository: Modern, Performance Oriented, Clean Architecture with isolated container layers

Today, I have released a project to production environment and made it opensource. Its opensource so anybody could check how modern prod-level Node projects looks like.Github LinkPR's are welcome !https://preview.redd.it/d01925ogk4251.png?width=1333&format=png&auto=webp&s=256dfeed3ec47777b020043850118bfbb1ac3036

Submitted May 31, 2020 at 05:11PM by onur_ozkan

What Is A Good Module For Dashboards?

I'm looking for a good module to build dashboards with a Mongo DB. Couldn't find a lot in the internet so I was wondering what r/node would suggest.Thanks

Submitted May 31, 2020 at 05:34PM by jfr_com

Best Nodejs Backend Framework 2020

View Poll

Submitted May 31, 2020 at 03:58PM by abhijitEZ

Sessions in Node #7 | Authentication in Node.js with Express and sessions | secure password login

https://youtu.be/x8Ea6VPs89o

Submitted May 31, 2020 at 03:22PM by prodcoder

A one-stop-shop for all learning resources Deno 🦕 ...

No text found

Submitted May 31, 2020 at 02:50PM by Swapsh76

Creating a search with multiple params

Hi Guys,I'm looking to create a search using express/mongo. The search will have multiple params which will all be optional. I'm building the API side first. Are there any good guides on how to build this? Do i literally just pass an object into a `collection.find`Client side I will just be building up the url based on what a user selects in a form.

Submitted May 31, 2020 at 02:00PM by Deviso

Cannot set headers after they are sent to the client

When I'm try to access the data on my view I get this error. Any idea where the problem is? I suspect that it might be something with the way I do the the authentication but I'm not sure.Error:Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:470:11) at ServerResponse.header (/Users/zvado/Desktop/Programming/javascript/DevSpaceR/node_modules/express/lib/response.js:771:10) at ServerResponse.contentType (/Users/zvado/Desktop/Programming/javascript/DevSpaceR/node_modules/express/lib/response.js:599:15) at ServerResponse.send (/Users/zvado/Desktop/Programming/javascript/DevSpaceR/node_modules/express/lib/response.js:145:14) at done (/Users/zvado/Desktop/Programming/javascript/DevSpaceR/node_modules/express/lib/response.js:1008:10) at Object.exports.renderFile (/Users/zvado/Desktop/Programming/javascript/DevSpaceR/node_modules/jade/lib/index.js:374:12) at View.exports.__express [as engine] (/Users/zvado/Desktop/Programming/javascript/DevSpaceR/node_modules/jade/lib/index.js:417:11) at View.render (/Users/zvado/Desktop/Programming/javascript/DevSpaceR/node_modules/express/lib/view.js:135:8) at tryRender (/Users/zvado/Desktop/Programming/javascript/DevSpaceR/node_modules/express/lib/application.js:640:10) at Function.render (/Users/zvado/Desktop/Programming/javascript/DevSpaceR/node_modules/express/lib/application.js:592:3) Controller:const GetMain = (req, res) => { const Auth = new AuthJWT() const dbContext = new DbContext().Initialize('projects'); let logged = Auth.IsLoggedIn(req) let data = Auth.GetUserData(req) if (logged) { let projects = [] let querryProjectsByUser = dbContext.where("creator", "==", data.username); querryProjectsByUser .get() .then((snapshot) => { snapshot.forEach((project) => { let title = project["_fieldsProto"]["title"]["stringValue"] let description = project["_fieldsProto"]["description"]["stringValue"] let date = project["_fieldsProto"]["created"]["timestampValue"] let owner = project["_fieldsProto"]["creator"]["stringValue"] let language = project["_fieldsProto"]["language"]["stringValue"] let id = project.id let tempObj = { title: title, description: description, date: date, owner: owner, language: language, id: id } projects.push(tempObj) }) }) .catch(e => console.log(e)) .finally(() => { data.projects = projects console.log(data.projects) res.render("Manager/Main", data) res.end() }) } else { res.render("/Auth/Login", { error: "You need an account to access manager!" }) } } Auth code:class Auth { IsLoggedIn(req) { const token = req.cookies.token; if (!token) { return false } else{ return true } } GetUserData(req){ const token = req.cookies.token; let payload = jwt.verify(token, 'auth') let data = { username: payload.username, admin: payload.admin, logged: true } return data } } module.exports = Auth View:extends ../layout block content h1 Manager if data.projects.length == 0 h1 You have no projects else each project in data.projects h1=project.title p=project.description p=project.creator

Submitted May 31, 2020 at 12:51PM by draganov11

What do you guys use for „admin“?

I really hope this question does not sound weird. Most of my apps are centered around a Frontend user experience. Users have data attached to them and so on. You build the backend/api for this and and have your database.If you want to manage this data, or let it be managed by the client, what are some ways to provide an admin Interface without building a whole new frontend.Most of the times I‘ve been using CMS systems for this, which makes sense in a lot of cases but the more individualized the data model becomes, the harder it gets to implement it.So in short: how do you build your Admin panels for custom apps? Are there any frameworks that I should look into that make it easy to integrate existing APIs/backendes?

Submitted May 31, 2020 at 01:04PM by maggiathor

Node fatigue: Is it worth investing type in the node ecosystem in 2020?

Last week my productivity has hit a new low. I've recently committed myself to switch from a python Django backend to a TS node js backend. Before that, I've gathered some fairly extensive experience with React and JS itself. Ever since committing myself to node I constantly seem to be in a race to keep up with new technologies: GraphQL / GraphQL Nexus, TypeORM, Prisma, Express, Fastify, Nest, Deno ... to name just a few.Coming from a very mature framework, I can't help but notice that a lot of these tools are pretty half baked often missing very essential/basic functionality. Yet, the whole community seems to be in a crazy hurry to adopt every framework in a matter of weeks/months. A lot of these tools aren't backed by big organizations that commit to maintaining them in a responsible manner.Don't get me wrong: I want to use JS / TS. I like the language and love the idea of becoming a true expert in the ecosystem -> But it's frustrating. It's hard for me to trust these tools and I'm beginning to doubt whether it is worth it at all. Does the node (deno?) ecosystem need to mature as a whole before it would be advisable to get into it? Have you guys experienced similar frustrations? Do I just need to power through?

Submitted May 31, 2020 at 10:41AM by memo_mar

Node fatigue: Is it worth investing time in the node ecosystem in 2020?

Last week my productivity has hit a new low. I've recently committed myself to switch from a python Django backend to a TS node js backend. Before that, I've gathered some fairly extensive experience with React and JS itself. Also, I finished a React + TS project. Ever since committing myself to Node, I constantly seem to be in a race to keep up with new technologies: GraphQL / GraphQL Nexus, TypeORM, Prisma, Express, Fastify, Nest, Deno ... to name just a few. I end up researching for hours and hours fearing to miss out or bet on the wrong "horse".Coming from a very mature framework, I can't help but notice that a lot of these tools are pretty half baked often missing very essential/basic functionality. Yet, the whole community seems to be in a crazy hurry to adopt every framework in a matter of weeks/months. On top of this, a lot of these tools aren't backed by big organizations that commit to maintaining them in a responsible manner.Don't get me wrong: I want to use JS / TS.I like the language and love the idea of becoming a true expert in the ecosystem -> But it's frustrating.It's hard for me to trust these tools and I'm beginning to doubt whether it is worth it at all. Does the node (deno?) ecosystem need to mature as a whole before it would be advisable to get into it? Have you guys experienced similar frustrations? Do I just need to power through?

Submitted May 31, 2020 at 10:44AM by memo_mar

What is AWS | AWS Tutorial For Beginners | AWS Training Video | AWS Tutorial

https://youtu.be/MHZM7L8I7x4

Submitted May 31, 2020 at 09:55AM by rogeralbornoz

Saturday 30 May 2020

WebTorrent Workshop: Learn WebTorrent and WebRTC

https://webtorrent.github.io/workshop/

Submitted May 31, 2020 at 01:48AM by feross

Distributing library via ES module

I recently released a small typescript library targeting node apps (express in particular).I know node support for es modules is very new, so I am packaging it as a commonjs module, but I am wondering if there is enough uptake of esmodules in the node community to consider migrating or even possibly packaging in both module formats.This is my first time releasing a library for others' consumption, so I'd really appreciate any feedback. I would be especially grateful if anyone could point me to some libraries that could be considered a "best practice" when it comes to distribution. Thanks!

Submitted May 31, 2020 at 02:05AM by karma_bank

How do you avoid copy-pasting when there's 1 action with a drastically different path?

index.jsapp.use('', routes); routes.jsapp.get('/comments', (req, res) => { }); app.get('/posts/:id/comments', (req, res) => { }); app.post('/comments', (req, res) => { }); app.delete('/comments/:id', (req, res) => { }); app.put('/comments/:id', (req, res) => { }); The issue is that I had to change '/comments/' to '' and then put '/comments' on every route except one. Is there a better way that I am not aware of?

Submitted May 31, 2020 at 01:09AM by jesusscript

Error: self signed certificate ?

I'm trying to get an app deployed to heroku. My app runs fine locally. When I run NODE\_ENV=production , heroku local and heroku open commands both throw "internal server error"s. The logs indicate it is the error in the title.I'm using a handful of npm packages. I'm honestly not too sure which one is providing the certificate. I would think it's dotenv but ?The github link: https://github.com/JoeCastr/budget_app

Submitted May 31, 2020 at 12:58AM by stewfayew

How do you define a schema for a comment in a microservices with two backends with one-database-per-service architecture?

I have a post backend and a comment backend and each have its own database. How should I define the schema for comment?const commentSchema = new Schema({ content: { type: String, }, author: { type: Number, }, date: { type: Date, } });

Submitted May 31, 2020 at 12:14AM by jesusscript

How to test a function that manipulates files and directories .

So I am creating a library and its project folder looks like this :project-folder ├─node_modules ├─src │ └─modules │ ├─private │ │ ├─privateFn1.ts │ │ ├─privateFn2.ts │ │ ├─ ... │ │ └─privateFnN.ts │ ├─fn1.ts │ ├─fn2.ts │ ├─ ... │ └─fnN.ts ├─package.json └─tsconfig.json Each fn*.ts default exports a single function which is intended for public usage.Each privateFn*.ts exports a single reference which is intended for private usage.I have created a module which when executed creates a file which :exports the default export of each fn*.ts with name fn*.imports nothing (i.e. the file is bundled and has no depedency).default exports an object which contains as properties all already exported functions.That module exists in its own project folder which does not contain the folder and file structure which I previously draw .1)The question is how do I test such a module ?I am completely noob on testing . I have never written a single test.2)Should I just write a test.js file which programmatically creates the folder and file structure and then programmatically tests the resulting file from the execution of the module ?3)I will be in need of deleting these folders and files afterwards because maybe I will need to rerun the test . How can I create a safe space for deletion of files and folders so I will not accidentally ?4)Is the name of such a test end to end test , but for back end ?5)Which testing frameworks do you use for node?

Submitted May 31, 2020 at 12:04AM by liaguris

How to secure your web applications

Part 1 Talks about how to secure the web applicationPart 2 Talks about how to secure the production environment of the application

Submitted May 30, 2020 at 09:31PM by kiarash-irandoust

All about top-level-await in JavaScript - Did Node.js copy Deno?

https://youtu.be/RSZmxC4QCNU

Submitted May 30, 2020 at 04:05PM by mehulmpt

Proplem with flash npm package

Now I add message to display on login page via flash Now the message display fine but if i go to other route it will keep that message how I can display it only one time

Submitted May 30, 2020 at 03:44PM by mohammedatef555

installing-yarn-npm-and-nodejs-on-centos-7-x86-64-genericcloud-qcow2-image-causing issue

I have to build the nodejs code on CentOS-7-x86_64-GenericCloud.qcow2 image. I'm trying to install node12, yarn1.22 on that image, but not getting any success. Node10 and yarn1.22 works fine. But we need node12 because during development node 12 is used. Getting below error for node12 and yarn 1.22. Any help would be appreciated. Thanks in advance. buffer.js:607 slice: (buf, start, end) => buf.utf8Slice(start, end), ^RangeError: Index out of range at Object.slice (buffer.js:607:37) at Buffer.toString (buffer.js:804:14) at Object.readFileSync (fs.js:408:41) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1219:22) at Module.load (internal/modules/cjs/loader.js:1049:32) at Function.Module._load (internal/modules/cjs/loader.js:937:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) at internal/main/run_main_module.js:17:47 {code: 'ERR_OUT_OF_RANGE'

Submitted May 30, 2020 at 02:29PM by rchaitali1

🐹 Create, develop and manage your projects through an accompanying graphical user interface.🎉

https://github.com/Routine-App/Routine

Submitted May 30, 2020 at 02:36PM by getspooky1999

RunSpace is in stable alpha now! https://github.com/runspacegit

https://v.redd.it/r5xzz0w1pw151

Submitted May 30, 2020 at 02:46PM by 0x77dev

I made a babel CLI tool which writes unit test cases for your node app. I hope many find this useful :D

https://github.com/Ghost---Shadow/unit-test-recorder

Submitted May 30, 2020 at 02:07PM by GhostxxxShadow

How would create a price comparison site?

How would you create a price comparison websiteIgnoring front end framework and the in and outs of building such a tool how would you go about building price comparison site, I am mainly thinking about the back end here. If you want to search products and pull prices from a site and they don't have an api available would you just scrape the content on a regular interval? Is web scraping the only way to do this without an api?

Submitted May 30, 2020 at 11:52AM by MajorAtmosphere

update user info in array

i am having an issue, i want to update hobbies as a array (like- {"hobbies":["running","dancing"]} )User is a model.router.patch('/userInfo', async (req, res) => { const updates = Object.keys(req.body); const allowedUpdates = ['userId', 'userImages','intrestedIn', 'hobbies'] const isValidOperation = updates.every((update) => { return allowedUpdates.includes(update) }); if (!isValidOperation) { return res.send({error: "Validation fail" }) } try { const user = await User.findOne({ _id: req.body.userId }, req.body) if (!user) { return res.send({error: 'Invalid user Id' }) } updates.forEach((update) => { user[update] = req.body[update] }) await user.save() return res.send({ user }) } catch (e) { res.send(e) } }) and output is that, but i want array(like intrestedIn output)​​`{"user": {"intrestedIn": ["Female"],"hobbies": ["{\"hobbies\":[\"dancing\",\"running\"]} "],"_id": "5ec71c43026b2f1d640b657f"} }`

Submitted May 30, 2020 at 10:52AM by Manisha_987

FREE Udemy Bestseller - NestJS Zero to Hero - Modern Back-end Development with TypeScript

TL;DR - free copy, unlimited claims, for three days. Once you claim it, it's yours forever. Stay home and learn something new! <3Click here to claim the course for FREEWhy are you doing this every month?In short - my course is a bestseller and I noticed that when I give out my course for free, it does not hurt my sales.--Hey there!Approximately six months ago, I published my Udemy course "NestJS Zero to Hero - Modern Back-end Development with TypeScript". The community here has received it very well. Within two weeks, the course became a bestseller.NestJS has become incredibly popular. With over 250k downloads per week on NPM, it is the #1 framework in terms of growth.https://preview.redd.it/b2efsl5rcv151.png?width=2252&format=png&auto=webp&s=4125b79ef05f53c7c9276a12f23061bfbadefdbbToday, the course is a best seller with a solid 4.7-star rating and over 20,000 students. **I want to give back to the community and give you the course for free (its yours forever). This is a great time to invest in yourself and learn something new.P.S. A new GraphQL + MongoDB has been added, adding one more hour to the course.https://www.udemy.com/course/nestjs-zero-to-hero/?couponCode=END_OF_MAYFeel free to send the coupon out to any Juniors or students who might need it.#spreadtheknowledge #keeplearning

Submitted May 30, 2020 at 10:14AM by WeinAriel

Node to Deno. Mystery solved. Animated version.

https://codepen.io/web2033/full/jObgyXx

Submitted May 30, 2020 at 08:20AM by web2033

Stripe - Is there a way to get the revenue of a product for current/specific month?

Right now I am creating multiple products with 3 subscription plans. I am looking for a way how to get the monthly revenue for a product.example: Product 1 has 1 new (5$) subscription and 2 current subscription for this month. I want to get a total revenue of 15$ for this month for product 1.I was reading the documentation and I can't seem to find anything about this.

Submitted May 30, 2020 at 07:40AM by raguy1143

Friday 29 May 2020

how to build nodejs application

hi,am new in node js. i have created jodejs application which have some api's. normally in web service we just publish and host it in iis. i just want to know how to build newly created my nodejs application to see the minified js file?

Submitted May 30, 2020 at 06:34AM by kasimacsys

Should I have separate server for API and another for website?

First sorry for all the posts .I've been having some issues when it came to building my client side web app.So initially I created an API which talks to a postgresql database. Everything fine there.The issue came when I started to work on the client side web app.My login endpoint returns a JWT token if successful.On the client I used Axios to handle requests to my backend API, I have protected routes where it requires a JWT token which it verifies and then grants access to the endpoint.From what I've read, it's bad to save this JWT token on the client.Also I've read that JWT tokens aren't ideal for handling sessions on a website.So since I'm using Axios to handle POST,GET etc on the client and can't send back the JWT token as a header in future requests and I can't set the JWT as a cookie in my API login endpoint.I'm starting to think maybe have a server just for my API and maybe another server for running my website on. So then in the future i can then also have other clients interact with the API.What's the typical way people implement this?

Submitted May 30, 2020 at 04:26AM by prgrmmr7

Firebase vs Socket.io + MongoDB

Hi, I'm planning to make a mobile application where users listen music and chat. For chat i need realtime API. Firebase is great for fast-start but it gets expensive. My questions are: 1. Can i deploy socket.io and mongodb for free to my server? 2. Which one is cost effective? 3. How many user can fetch data at the same time from my average server? 4. Are there any good source that i can look for?

Submitted May 30, 2020 at 02:09AM by teyyihan

Verify Sign In With Apple using Node

https://youtu.be/D2W9eow6ajY

Submitted May 30, 2020 at 02:14AM by mehulmpt

JWT with Backend API

I'm a bit confused so I currently am creating a JWT token upon login on my backend api.my protected routes require this JWT token as a header.I'm a bit confused as how it all goes together, I assume I should be setting the JWT token as a httpOnly cookie but how would I set it as a header in future requests via Axios in js on the client?

Submitted May 30, 2020 at 01:15AM by prgrmmr7

Worker threads inside microservices

Should worker threads be spun up inside the backend or should worker threads have its own backend that serves other backends, and also does it make sense to have worker threads if you can spin up several instances of any backend? I am trying to understand when to use worker threads inside a microservice architecture and how you can optimize a microservice architecture. Also, is spinning worker threads inside a backend in a microservice considered to be an anti-pattern?

Submitted May 29, 2020 at 10:27PM by jesusscript

Any good book on how to build a really complex microservice application with Node?

I am looking for something other than building an ecommerce application since my last 3 projects involved building an ecommerce application, like a POS system or something like that.

Submitted May 29, 2020 at 10:33PM by jesusscript

Why can't I install v8-profiler?

Host Your Portfolio Website and Personal Node.js Projects on a Single VPS

https://maximorlov.com/host-your-personal-projects-on-a-single-vps/

Submitted May 29, 2020 at 06:31PM by _maximization

Review of Loopback 4 compared to other node.js framework

Hey guys,Has anyone used loopback 4 ? I have been using loopback 3 for several of my production app.Once I started getting a hang of it ,it was very easy to work with.But loopback 4 has completely been restructured and it looks very complicated ,but the support for inbuilt typescript,swagger,ES7and other features like dependency injection looks promising.I would love to get your opinions of anyone has used loopback 4 or if anyone can recommend a similar framework with inbuilt ORM,swagger API explorer and making APIs instantly through a CLI.Thanks in advance

Submitted May 29, 2020 at 06:14PM by melgo44

What the hell does architectural patterns of high-scale applications mean, and can you name a few example?

5+ years of experience designing, building, enterprise-grade or consumer-facing software Exceptional coding abilities and experience with architectural patterns of high-scale applications I saw these two requirements at a job posting and I had no idea what they really meant. Can someone explain to me what I need to learn to meet those two requirements specifically?

Submitted May 29, 2020 at 04:50PM by jesusscript

New eBook: Mastering Mongoose - thecodebarbarian.com

http://thecodebarbarian.com/new-ebook-mastering-mongoose.html

Submitted May 29, 2020 at 04:50PM by code_barbarian

How to go about setting up a server for updating data and fetching it through an API? (long plan)

Hello,So I have a node.js program that scrapes data from a website.My current plan is:Scrape my chosen website for data (done)Set up my database which is updated through cron job dailyI'm considering using MongoDBLaunch my node.js program on a hosting platform and connect the database to it.What I am unsure about is which hosting platform would be the best for publishing it. I have looked at tutorials for publishing on Digitaloceans and thought it was pretty good (but it is paid.) I am familiar with Heroku but because it is free it is pretty slow.Create a REST API to fetch information from the databaseI would be able to create the rest API and keep it on the same server right?I'm pretty new , so there may be things that don't make sense in the plan.​Thanks in advance : )

Submitted May 29, 2020 at 03:51PM by nebling

Express async error handling

Sorry if this has been posted before. I’ve just started learning Node and I am trying to write a basic mysql CRUD rest api.I basically got quite confused about how to handle errors in express. From what I read, one can either send all the errors to the error handling middleware by doing next(error) or monkey patch using express-async-error to allow direct throw in try catch block.My confusion is mainly around how to handle errors coming from db. Example I have a function which creates an entry in the database and I’m using try catch block to catch any errors result of the query. Now, I would connect the query function to my main controller function which would also be in a try catch block.Do I need to next(error) on both the db and controller functions? Or can I just return the error at the db level and handle the error at controller level?

Submitted May 29, 2020 at 04:05PM by jjbunny22

Having trouble with passing data from database to handlebars view

I'm passing some data from a postgres database with sequelize to my handlebars view. The data is passed but I'm not able to display it as I think I'm supposed to be able to do.This should be all the relevant code, if anything else is needed please let me know.Router code:router.get('/:name', (req, res) => { var userName = req.params.name; User.findOne({ where: { name: userName } }) .then(user => { res.render('user', { user }); }) .catch(err => console.log(err)); }); Handlebars view:This is where I'm having problems, this code:results in an empty paragraph. Logging it with outputs undefined.​This code however: results in 6 paragraphs, the last 4 of which are empty. Logging it results in it outputting 6 times, the first two are the name in the databaseTest Name // correct result Test Name // again, correct result undefined undefined undefined undefined ​The console displays no errors.

Submitted May 29, 2020 at 03:36PM by Rayeth_

Populating complex objects

/r/mongodb/comments/gss4v1/populating_complex_objects/

Submitted May 29, 2020 at 01:32PM by Administrator101

Google authentication with Node.js and Passport.js

https://www.loginradius.com/engineering/blog/google-authentication-with-nodejs-and-passportjs/

Submitted May 29, 2020 at 12:40PM by puneetsingh24

A bit confused newbie nodejs developer..... Looking for some advise

A bit confused newbie nodejs developer.....Causation: This is a bit long question .Some BackgroundI have bachelor degree in Electrical Engineering(2018 pass out). Unfortunately i never done coding during my college time . In October 2018 i started working in a company as consultant .I learnt some basic MySQL there.After that in may 2019 along with one of my friend i tried my hand in entrepreneurship and decided open a startup ,So along with my friend i did market research on various ideas but nothing worked. In mean time we got a project of building an app(video on demand streaming ) for android devices. We started work on it an august 2019 and as we were new it took us long time to complete it .i started working on back-end ,We decided nodejs as working technology. I never had done any coding in node js at that time ,So i started learning and applying things to Project while reading a book https://www.amazon.com/Getting-Good-Javascript-Andrew-Burgess/dp/0987102672 and another book in which i read express and node js part as our back-end database was mysql https://www.amazon.in/Node-js-MongoDB-Angular-Web-Development/dp/9352865502/ref=sr_1_3?dchild=1&keywords=mean+stack&qid=1590744608&s=books&sr=1-3After Completing project in November 2019 ,I left startup and tried to learn at home ,After that i completed this course (https://www.udemy.com/certificate/UC-CNPPLRZI/ ) advanced java script course and another course ( https://www.udemy.com/course/the-complete-web-developer-zero-to-mastery/learn/lecture/16538776?start=0#questions ) this course have html , css , javascript and node js .This is popular course on udemy .After that i started applying for job in node js through naukri.com. Fortunately i received some phone calls for the interview but was not able to convert those into opportunity . Blunder 1 i got a job in January 2020 but they asked me to work on php and i thought I can get job in node js , so worked there for 15 DAYS and left.After that i started reading this book ( https://www.amazon.com/Web-Development-Node-Express-Leveraging/dp/1491949309 ) but never completed and meanwhile applying for the job.Blunder 2 After that i seek help of my friend they suggested me to get strong in algorithms and start solving problems on (https://www.interviewbit.com/practice/ ) i did some problems for about 20 days ,These problems are hard af. And i needed a language to start with so i learnt python. Along with that he advised me to learn java as there are very few company that works in node js .So i gave about 50 days to java and Algorithm and did this (https://sp19.datastructur.es/ ) this mooc course .​Blunder 3 After that i started applying for job as java developer .Did't get any response so again i started working with nodejs.And i started this course (https://developer.ibm.com/articles/learn-node-unit-1-overview-nodejs-learning-path/) but this course seems to be pretty advance to me After completing 6 modules . i decided to do some hands on practice so i built map based from this tutorial (https://www.youtube.com/watch?v=J7pFiXh-ydA&t=13747s ) just yesterday.Short term goalShort term1 To get a job as node developer.Long termTo do MS from some prestigious university in computer science after getting at least one year of proper experience in computer science .Questions now0.Can i some how get back to track after so many blundersShould i continue to do some project while watching you-tube videos.2.Should i read books to get more knowledge about node js (As i'm still newbie) and if so which books should i read .3.Should i start working in my previous company as consultant again .4.Any other advice you want to give me ,Are welcomed and i seriously need some advice.

Submitted May 29, 2020 at 11:06AM by mysterious_code

Does anyone know how to store usernames in MongoDB using Mongoose JS?

Sorry I am new to the backend side of things so I am slowly learning. But could anyone provide any sort of links, suggestions, or videos that show how to store usernames inside of MongoDB using Mongoose JS?I am just learning so I appreciate all those who are able to help. Thank you all so much!

Submitted May 29, 2020 at 09:37AM by jazilzaim

Doubt regarding websockets

I am working on a website that requires Instant Messaging and real time notifications. I decided to use socket.io to achieve this but I'm facing a few challenges.It has an existing RESTful API. I'm only allowed to work on the same. Is it okay to integrate socket.io into the same API?The website has two portals and these portals have separate frontend (2) and backend (2) APIs sharing a same database. Data flow should be, Frontend1 > Backend1 > (Backend2 >?) Frontend2 Is it possible to use socket.io in this scenario?If it's not the best way, any suggestions would be appreciated. Thanks.

Submitted May 29, 2020 at 08:38AM by ShekStorm

JSON Web Tokens Suck (video + post). Do you agree?

(First of all, I want to make it clear that I have no idea whether he's right or wrong. That is precisely the reason I am posting this).Randall Degges is an experienced security expert and he did this talk, which is actually pretty entertaining to watch and very well presented, which nice slides and stuff:https://www.youtube.com/watch?v=pYeekwv3vC4​I got back to the web dev industry not along ago, so all of this is new to me. That's why I am now extremely confused. Basically, he says that Session Cookies beat JWT in pretty much every department when it comes to login systems.Since most people probably won't watch a one hour video, he also posted this on Github (and got most upvotes for it):​"This is a really interesting topic. The talk linked to above is my talk which I'm always happy to discuss. It's quite hard to sum it all up into a short Github comment though.The gist of it is this:JWTs are larger than randomly generated API tokens because with JWTs you store data in them for stateless benefits which increases their size. Bigger size means more latency from the user to your API which means slower connections. And... If you aren't storing data in the JWT and are using it purely as a random string then you're negating any benefit they might have at all. Now they're just oversized string IDs.JWTs, by design, are meant to be used to store cached data. That's their only use case in the entire world. And that is exactly what you don't want to do if you're building a secure web service: a website, API, IoT device, or anything in between. From the moment you decide to start caching authentication and authorization data in a client-side token you've opened yourself up to security issues because you're trusting that the data you receive is correct and valid. And... If you don't trust that data (or want to revoke tokens when needed) then you need to build some sort of centralized revocation list which again: negates any benefit you might have gotten from a JWT in the first place. This goes back to the original security vs. speed argument: it is truly impossible to have a secure anything if you're using cached data to validate your user.Setting a short-lived JWT TTL is basically a shitty way of saying that "I want security and speed" but really accomplishes none of either: if you have a short-lived TTL you're still vulnerable to using invalid cached data and you most certainly won't be able to revoke tokens when needed (and if you can... then you are using centralization again and negating all JWT benefits).Finally: if you realize JWTs are basically security anti-patterns but still want to use them you might think "OK: I'll just use a JWT but I'll only use it once and never rely on cached data." But if you do this then it goes back to argument 1 -- JWTs are simply less efficient API keys (or session IDs). They're accomplishing the same thing except with extra complexity/size over the wire which serves nobody any good and only complicates something simple.In pretty much every single situation imaginable JWTs are worse than just using a randomly generated API key of some sort (or session ID if we're talking about web apps). There is no benefit to using them, only downsides.Instead of using JWTs my recommendation is to keep it extremely simple:If you're building a web app of some sort use server side sessions and store a cryptographically signed (and optionally encrypted) session ID as a randomly generated string on the client. Cache session data with invalidation in the backend if you want speed.If you're building an API service of some sort generate random string API Key IDs and Secrets as key pairs for your users. Follow the same rules above: cache things server side if you want with invalidation for speed.If security is a major concern: store API key secrets hashed using a fast algorithm (intended to allow for many concurrent lookups without hammering CPU/memory/cores with "good" algorithms like argon2, scrypt, and bcrypt). This way key secrets are unrecoverable (like what AWS does) and you can trust them slightly more."​Both the video and the post got me really confused, since there are a bunch of tutorials out there encouraging you to use JWT's for login systems.Some people say he made this video because he works for a company that offers a paid login service, but that is not really a valid/strong argument against his statements.That is why I would like to know what you think about all these claims.

Submitted May 29, 2020 at 08:02AM by Paullang18

Fastest socket.io alternative? - or ways to boost performance

Hey all,First I wanna say this is kind of a re-post, but it's been 4 years since the last post and my problem is more performance centered. So, I want to get the communities opinion on the state of things. Here is the original post in case anyone was curious.​I'm working on a project that is currently running on Socket.IO, and it has worked beautifully for my needs until now. I'm at the point where I'm running some stress tests and the framework seems to be the component failing me.​My server has a loop that handles data and calculations to push to the clients and it significantly slows down after around 50 connections with around 20 emit/second each. I recognize this is a lot to push to each client, and since I've been struggling with performance I'm rewriting some things to try and keep up with 20 emits/second but to multiple clients at once but with more data in each emit. This is nice and worth the effort regardless of performance concerns but as more clients connect and their data overlaps less performance returns to 20 emits/second per client.​I've read this kind of performance can be expected since Socket.io can be needlessly slow in my use case (it isn't a necessarily lightweight library and because of fallbacks in particular), also note: I'm running this on a pretty tiny server currently, but I'd like it to be able to run on something this lightweight even if I'll be upgrading in production.​Is there anyway I can optimize socket.io to drop some of its baggage to increase emits/second? This is also my first time really using anything ws, would some sort of stream based library be better for my case? I'm also almost exclusively publishing to rooms and namespaces as opposed to directly emitting to clients, I understand this can be wasteful and slower, but would direct emitting really be a significant performance boost? (This would be hard for me to switch to test.)​For something to be a good alternative I'll need scalibility (load balancer support, I guess) and an event emitter or namespace/room support (but both is a major plus). Also worth noting I'm pushing data from server --> client, but also a little (albeit much much less) from client --> server.What I don't need is support for is older technology and outdated browsers, they can be kept out, as well as people with strict firewalls. I also don't particularly care for reliability (my IO/s is high enough that it's okay to lose some packets from time to time). If I didn't mention it or it doesn't seem important to my use case, I probably don't need it.​My goal is to achieve at least 100 socket connections sending 20 updates per second each. With the ideal number being 500 socket connections sending 20 updates per second each.Question: Which WS (or other framework if they exist) engine can produce the largest IO/s from server-->client?TL;DR: I want to send all connected clients data 20 times a second EACH (or batches of clients). Which library has the best support for this?Thanks!

Submitted May 29, 2020 at 08:06AM by DivineActions

Thursday 28 May 2020

How OWASP security practices can be applied to Node.js

https://dzone.com/articles/10-nodejs-security-practices

Submitted May 29, 2020 at 07:36AM by Owns-E

Deploy an Express + React app

Hey devs!After one month working on a full-stack project (express.js/react) I finally finished it and now I need to deploy it somewhere.In my project folder I have:-frontend-folder-backend-folderMy front-end (port 3000) is consuming my API (port 8000) and everything is working just fine.The only place I ever hosted something was Heroku.Since I want the app hosted on the same server, can someone point me in the right direction of what I should study/learn about it?I saw something about using Digital Ocean with (?) Nginx, but honestly, I am lost!Thank you for your help! :)

Submitted May 29, 2020 at 07:05AM by lucasmrl

Hey, I made a web app to look up public repos from multiple version control platforms. I'd love some feedback!😄

​https://i.redd.it/bhhdwj7a0n151.gifHere's the link to the Heroku deployment - https://gitwiz.herokuapp.comand the link to the repo - https://github.com/KSSBro/gitwiz

Submitted May 29, 2020 at 06:12AM by iamkss

Cannot connect to MySQL using shell.exec

I have following code ::const shell = require('shelljs')shell.exec("mysql -umall_stage -p'783452' -h10.258.40.90 testDB");When I run this code I get message :mysql: [Warning] Using a password on the command line interface can be insecure.After this, I get no response it gets stuck here. But when I run the command directly I get the same warning and I get connected to DB. Is there any reason why it's not working through code?

Submitted May 29, 2020 at 06:31AM by GhostFoxGod

Any basic use case for a microservice system with 2 node backend?

Any basic use case for a microservice system with 2 node backend? I want to build a bunch of applications to test out a kubernetes cluster, so I need to implement a dozen of basic apps that are not too trivial and could be used in the real world.

Submitted May 29, 2020 at 05:22AM by jasonscript

What would you improve?

https://try.gitea.io/nadal/repository​Used this in a coding challenge after a job interview. I didn't get chosen, but I was wondering if it was because of the code quality in the project.const express = require('express'); const app = express.Router(); const repository = require('../repositories/ExpenseRepository');/** * Get a list of expense objects * @method * @param req request object * @param res result object * @returns {Promise} json of expenses * */ app.get('/', (req, res) => { repository.findAll().then((expenses) => { res.json(expenses); }).catch((error) => console.log(error)); });/** * Post an expense object * @method * @param req request object * @param res result object * @returns {Promise} json of expenses * */ app.post('/', (req, res) => { const expense = { description: req.body.description, amount: req.body.amount }; repository.create(expense).then((json) => { res.json(json); }).catch((error) => console.log(error)); });/** * Deletes an expense object * @method * @param req request object * @param res result object * @returns {Promise} empty json * */ app.delete('/:id', (req, res) => { const { id } = req.params; repository.deleteById(id).then((ok) => { res.status(200).json([]); }).catch((error) => console.log(error)); });/** * Updates an expense objects * @method * @param req request object * @param res result object * @returns {Promise} empty json * */ app.put('/:id', (req, res) => { const { id } = req.params; const expense = { description: req.body.description, amount: req.body.amount }; repository.updateById(id, expense) .then(res.status(200).json([])) .catch((error) => console.log(error)); });module.exports = app;This is the "central" part of the application, so I am wondering if there's anything wrong with it. Is there anything that can be improved upon? Try to be as nitpicky and harsh as possible.

Submitted May 29, 2020 at 03:01AM by wonderfulnadal

Why would I use Node instead of something like React or Angular?

If I have a site that's going to make some api calls and display data from those calls what would benefit me to use Node instead of other front end frameworks? I'm new to these and looking for clarifications on differences?

Submitted May 28, 2020 at 11:58PM by laneherby

Am I thinking of this wrong?

So I built out a login route and it works great and all but my question is currently my login route responds back with 'response.header('auth-token', token).send(token)' as an example.My question is when a user logs in from a web page form dont't i need to have some sort of redirection? and also if i include the redirection then how would I use the same code for logging in via iOS app client?Do I make two login routes? One for website one for app? Doesn't seem right as its the same code..

Submitted May 28, 2020 at 09:43PM by prgrmmr7

Using an external library

I have been able to use the FFI npm package to call methods in a .so file. Is it possible to configure the FFI npm packages to use a DLL file instead?This does not work:import ffi from 'ffi'; import ref from 'ref'; const int = ref.types.int; const testPlugin = ffi.Library( './lib.dll', { add: [int, [int, int]], }, ); const result = testPlugin.add(2,2); I get the error:/Users/desk/src/temp/node-cs-interop/service/node_modules/ffi/lib/dynamic_library.js:74 throw new Error('Dynamic Linking Error: ' + err) ^ Error: Dynamic Linking Error: dlopen(./lib.dll.dylib, 2): image not found at new DynamicLibrary (/Users/desk/src/temp/node-cs-interop/service/node_modules/ffi/lib/dynamic_library.js:74:11) Thnx

Submitted May 28, 2020 at 09:28PM by programmer-bob-99

The N-API bindings for GLFW

Multi-platform library for creating an operating system window.You can create your own desktop application based on Node.js and OpenGL/Vulkan API.https://github.com/Reon90/glfwJS

Submitted May 28, 2020 at 07:19PM by reon90

Using python with node.js

I am new to Javascript and for my current project I need to use some functions I wrote in python. How should I execute a specific function in python from the main body of my project in node?

Submitted May 28, 2020 at 06:46PM by crazy_cookie123

Why are there executables (.exe) in my node_modules?

TIL: While running a code scanning tool at work, i discovered several of my packages contain .exe files. why are these present?

Submitted May 28, 2020 at 06:47PM by addijhaq

Relation between Users and cryptodata Sequelize database

COIN.js module.exports = (sequelize, DataTypes) => { const Coin = sequelize.define('Coin', { cryptoName: DataTypes.STRING, }) return Coin } ​USER.jsmodule.exports = (sequelize, DataTypes) => { const User = sequelize.define('User', { firstName: DataTypes.STRING, lastName: DataTypes.STRING, email: { type: DataTypes.STRING, unique: true }, password: DataTypes.STRING }, { hooks: { beforeSave: hashPassword } }) return User } CoinUserRelations.js const User = require('./User.js') const Coin = require('./Coin.js') module.exports = (sequelize, DataTypes) => { const CoinUsersRelations = sequelize.define('CoinUsersRelations', { UserID: { type: DataTypes.INTEGER, references: { model: User, key: "UserID" } }, CoinID: { type: DataTypes.INTEGER, references: { model: Coin, key: "CoinID" } } }) CoinUsersRelations.belongsToMany(Coin, {as: 'Coin', foreignKey: 'CoinID'}) CoinUsersRelations.belongsTo(User, {as: 'User', foreignKey: 'UserID'}) return CoinUsersRelations } ​Hello, so my issue is a bit weirdCoinUsersRelations.belongsToMany called with something that's not a subclass ofSequelize.Model atFunction.belongsToMany ​and I was wondering why does it not understand that I want to create relations between these 2 tables..

Submitted May 28, 2020 at 07:02PM by gjellbi

How To Automatically Bump NPM Package Version

https://medium.com/@PhilipAndrews/how-to-automatically-bump-npm-package-version-feee0e4dde6f

Submitted May 28, 2020 at 05:49PM by likeaspacemonkey

Extract text from image.

https://www.monkwhocode.com/2020/05/nodejs-extract-text-from-image-using.html

Submitted May 28, 2020 at 03:18PM by saurabhDvara

Use classes or functions in Express ?

I have used classes and functions but I am confused what is a preferred thing to use. I find functions more easy, I'm not really good in OOP. What do you guys prefer in your projects?

Submitted May 28, 2020 at 03:01PM by one_lame_programmer

Sessions in Node.js #6 | Express.js tutorial | Authentication in Node | Password Hashing with bcrypt

https://youtu.be/i6190xVJMh8

Submitted May 28, 2020 at 03:07PM by prodcoder

How do I modify this code to prevent the CPU from spiking so hard?

https://i.redd.it/syg5t2m7bi151.gif

Submitted May 28, 2020 at 02:23PM by amazeguy

Mange DB cost with real time location

i am having in trouble, when client provide real time location (with socket.io), whether i have to update regularly in DB or not?​if i update regularly in DB then cost of DB will increase or not?​if yes, then how i reduce my cost of DB?​example- i am making an app like if someone comes to near me (uses same app) then i it show me who comes. (like- Uber,Ola,Happn crossed path, Swiggi etc.)​can i have some help?

Submitted May 28, 2020 at 01:07PM by Manisha_987

Collaborators for project

I am building a marketplace that connects the local stores to their customers and the stores to wholesalers. It would be an amazing learning experience and since I have just started the development it would be easy to join as soon as possible.Lot of things to learn - Front End , Back End , Cross Platform mobile development, UI/UX, Database etc.Basically we will be creating a Mobile App and Web AppFor Stores and Customers( Yeah 2 separate modules ).Tech Stack -FlutterVue.jsNode.jsExpress.jsMongoDBAny one with knowledge of any technology is more than welcome to join. Comment your excitement level from 1 - 10 and your country. If you are interested in creating such a thing. I will be more than happy to share the resources. And let's see what we can learn from each other.I have done the work of listing the functionality what we will be creating suggestions and Ideas are more than welcome.

Submitted May 28, 2020 at 12:26PM by icewalker2

MongoDB Mongoose not saving all parameters

I have a schema as seen here:var schema2 = new mongoose.Schema({email: "string",name: "string",projectname: "string"});And a model here:var newproject = mongoose.model("pages", schema);Then I say what I want to save:var page = new newproject({email: req.body["userid"],name: req.body["statuspagename"],projectname: req.body["project"]});Then save it:page.save(function(err) {if (err) {console.log(err);} else {console.log("page created!");}res.send("Page created!");});But it doesn't save the 'projectname'. If I `console.log(page);` it also doesn't show in that. How come 'projectname' isn't showing?

Submitted May 28, 2020 at 11:13AM by EddiesTech

Node app hanging when server is started

Hi guys, am in a bit of a problem here, my node app seems to hang all the time when i start the server. Imma leave a link here. Am sorry though i actually pushed the node_modules too, sorry :( Thanks in advanceThe link

Submitted May 28, 2020 at 09:42AM by quavo101

Is npm package installation significantly faster on an SSD drive ?

For example commands like create-react-app and making angular apps ?

Submitted May 28, 2020 at 09:45AM by amana_araragi

Keystone generator for v5?

Hi all. I just started my adventures with keystone js, and I came across a neat keystone generator that saves a lot of time, however it uses v4 beta version and many of the dependencies are outdated there. So I was wondering if there is a generator with v5 or how do they go about it with the new version? Thanks in advance.

Submitted May 28, 2020 at 08:43AM by technician_harlan

Is Redhat's Openshift free plan good enough for doing some scraping?

Basically, never did any scraping other than locally. The maximum time I scraped something was like 9-10 hours consecutively from my local IP without any proxies.I'd like to scrape some data & would love to know if the Redhat's Openshift free plan good enough.If not, is there any service which allows scraping, preferably free?

Submitted May 28, 2020 at 08:48AM by deadcoder0904

Mail authentication with Node.js

I am sort of new to Node.js. I have worked with phone number auth (using Vonage/Nexmo API) and JWT for user sessions so far. Now I want to try email. Email seems a bit more challenging since I got to have my own email server (unless I read that wrong) and use that. Is email really more challenging than phone authentication? Do I need a web domain first to get started? Does Mailgun or some other email provider offer an email server as well or do I need to do something like configure it on Google Cloud?I appreciate those that do give a response and try to help. Thank you all so much! :)

Submitted May 28, 2020 at 08:30AM by jazilzaim

Wednesday 27 May 2020

New Features & Improvement in Node version 14

https://www.angularminds.com/blog/article/Improvement-features-of-node-14.html

Submitted May 28, 2020 at 07:17AM by EllaNicholls

Question regarding objectID and mongoose

Hi,I'm starting to learn nodeJS + mongoose and let's say I make an arbitrary endpoint like /blogs/:blogId, I want to return a 404 whenever it the id is not found, but if I type in anything that isn't a objectID for blogId it throws an exception? How can I get around that? I want to be able to throw a 404 for say the value 1 or 2 even if it isn't a valid objectID?

Submitted May 28, 2020 at 05:24AM by wastedtimez

What do you guys use for authentication/session handling?

Hello everyone,I'm building a backend for an ios app but i also want to have a login via website and I have a few api endpoints set up now and was thinking how I should go about handling user login authentication and sessions.Any tips on what I should do/use?

Submitted May 28, 2020 at 01:30AM by prgrmmr7

Blog Post Suggestions

I am stuck and can't figure out what my next blog post should be. Do you have any suggestions about what I should write or what you would like to be published etc. It can be a topic explanation, js, node or react project building or a bug that you face. Thank You

Submitted May 27, 2020 at 08:18PM by noharashutosh

What npm module(s) do you use to sanitize user input?

No text found

Submitted May 27, 2020 at 07:54PM by SuperbArrival

I made deadbolt – a one-click file encryption app built on electron

https://github.com/alichtman/deadbolt

Submitted May 27, 2020 at 07:03PM by aaronlichtman

Denoify: For NPM module authors that would like to support Deno but do not want to write and maintain a port.

https://github.com/garronej/denoify

Submitted May 27, 2020 at 07:00PM by garronej

Deta Base: the database for side projects

Hi r/node,I’m Max, working with a small team in Berlin, and I’m excited to announce the launch of Deta Base, to r/node (in the case you haven’t seen us on Product Hunt / Indie Hackers).My teammates and I at Deta think the modern cloud is amazing, but also a complicated mess. For getting a (small) idea out quickly, one shouldn't spend time fighting with servers, YAML files, etc.Base is our first swing at this problem. With Base, not only do you get started within a few seconds, but you still get the features you’d get from a “big cloud”: blazing fast read/writes, high scalability, security, backups, and support for complex queries.We’d love r/node’s feedback on Base, and more than happy to answer any questions!Links:signup: https://web.deta.sh/site: https://www.deta.sh/docs: https://docs.deta.sh/npm: https://www.npmjs.com/package/detaAn early user’s feedback: https://twitter.com/jajoosam/status/1265647837041197056Thanks!Max and the Deta Team

Submitted May 27, 2020 at 05:53PM by eubreezy

Collaboration platform

https://imgur.com/gallery/sEp3UiX

Submitted May 27, 2020 at 12:04PM by rubens33

I built a site to sell npm packages

https://privjs.com

Submitted May 27, 2020 at 11:39AM by Mesthabro

knex, postgress, receiving wrong info?

hi, i'm a selftaught noob with bad english skillsi'm having a problem where i'm not receiving the data that i'm expectingi have a database with 3 tables,object table => wich contain objects that can have multiple contacts,contactPerson table => wich contains contacts that can be the contact person for multiple objectsso i thought this was a "many to many" relation so i made a "linker" table wich contains the 'object_id' & 'contactPerson_id' as foreign keysconst joinFields =['object_name','serial_nr','contact_name','email','phone_nr']; async get(param){ const object= db('object') .join('linker','object.id','=','linker.object_id') .join('contactPerson','linker.contactPerson_id','=','contactPerson.id') .where(object_name','ilike','%'+param+'%') .orWhere('serial_nr','ilike','%'+param+'%') .select(joinFields); return object; }, when i run this code i expect to recieve one object that matches the name/serial with all the contact persons for that objectinstead i receive 2 objects (the same one) but each time with a different contactPersonwhat am i missing, wich direction should i search to create it like i want it (1 object with all the contacts)thnx

Submitted May 27, 2020 at 11:19AM by sageza

is this code for using static assets in express correct?

code:app.use('/static',express.static(path.join(__dirname, '/public')),(req,res,next)=>{ console.log('somebody was here') next(); });

Submitted May 27, 2020 at 10:54AM by philosopher_supreme

Which server-side programming language is the best for a starting programmer: Perl, PHP, Python, Ruby, JavaScript (Node), Scala, Java, Go, ASP.NET, or ColdFusion?

Luis M. Gonzalez, I love Python — I recommend a dynamic scripting language over a statically compiled one, since they're easier to learn and use and are much more productive and fun. … That leaves out Java, S..

Submitted May 27, 2020 at 10:09AM by UnfairCost

Dockerization of NodeJS Applications on Amazon Elastic Containers

https://blog.soshace.com/dockerization-of-node-js-applications-on-amazon-elastic-containers/

Submitted May 27, 2020 at 10:19AM by branikita

What does a "node" in coding mean?

No text found

Submitted May 27, 2020 at 09:45AM by UnfairCost

Node Js: Can I integrate Node Js with WordPress? Is it possible?

I might late to answer this question but I want to give it a try. You can integrate node.js with WordPress. Same I did for CakePHP + node.js.But for the question was, WHY? Why I should integrate node.js in PHP. And the reason was I need to perform an async operation that’s why I pick node.js.Can it be done on PHP too? Of course, the same I can easily achieve on PHP but I wanted to move completely from PHP to node.js, that’s why I pick node.js for my upcoming language.

Submitted May 27, 2020 at 09:26AM by NewSoup3

Build a QRCode API and Inventory Management System with Autocode and Airtable

https://medium.com/@janeth_10755/build-a-qrcode-api-and-inventory-management-system-with-autocode-and-airtable-7ec23149cd23?postPublishedType=initial

Submitted May 27, 2020 at 07:57AM by JanethL

Tuesday 26 May 2020

How to see default cipher suite of my node.js?

There's legacy Node.js project using Node version v6.9.5 and OpenSSL 1.0.1f. It doesn't use any crypto/tls/ssl libraries. It uses the request library to call external API from another website. I want to see the cipher it uses when sending these requests. I tried printenv but theres no variable called NODE_CIPHER_LIST or NODE OPTIONS etc and tried looking for default cipher suites of Node version 6.9.5 but there's no specific list, only general list like thisHow can I figure out the ciphers it used when sending requests to this external API? When I search for cipher keyword in my source code, there is none. or is it possible that it doesnt use ciphers at all?

Submitted May 27, 2020 at 07:09AM by crimson_xx0

Using Azure Storage + lowdb and Node.js to manage state in OpenFaaS functions

https://medium.com/@therealburningman/using-azure-storage-lowdb-and-node-js-to-manage-state-in-openfaas-functions-5776f214e84d

Submitted May 27, 2020 at 06:41AM by therealburningman

Convert Java to node.js

While I know there is no such “tool” that would convey, am looking more from good resource(s) to refer to convert part by part the java code have written into node.jsThis java code contains Classes, methods, package imports etc

Submitted May 27, 2020 at 02:40AM by sidlas86

June 2020 Security Releases

https://nodejs.org/en/blog/vulnerability/june-2020-security-releases/

Submitted May 27, 2020 at 01:19AM by dwaxe

Free udemy courses 100%off for limitd period

Hi This is some courses from udemy i wanna share it with u :) Hope this can be help u. Link:https://www.myfreeonlinecourses.com/2020/05/new-free-udemy-courses-100-off-coupon_26.html

Submitted May 27, 2020 at 12:52AM by yassine90

[Help] Project architecture definition

Hello, I'm a developer (with 1 year experience and impostor syndrome) seeking help to define the architecture for a new project.My boss assigned me to a new project where I need to build a comercial web application, with a subscription fee, which can be installed locally on a client's network, and will mostly do relational database processing (SQL Server, Oracle, MySQL).The core functionality of the project is already built in SQL language. But someone with access to the database would have access to the source code using a SQL profiling tool, so we must translate that SQL functions to a language that can be compiled to hide the sourcecode from the users.So the main things to keep in mind for the architecture is:Hide the sourcecode from customers. The customers will likely have tech team, so we don't want anyone snooping around the sourcecode.The architecture should be database friendly, what I mean by that is the back end language should have lots of functionalities or packages that handle database manipulations.The application should be subscription based, so if a customer stop paying we need to remove their access even if the application is installed locally.So these specifications raised some questions for me:Can I use TypeScript with PKG package to compile the javascript to a binary. Is it as safe as using another compiled language? or should we pick another compiled language?Can Python be used alongside Cython to compile it? Is Python a suitable language for manipulating databases? (I ask this because the guy who made the core functionalities is not a web developer, and only has affinity with Python environment, so maybe he would suggest using Python)Is it possible to make sure users will only use the application as long as they're paying, even if their application host is not connected to the internet. Maybe use a serial system, or a prepaid system?any suggestion or comment is welcome.Thanks in advance.

Submitted May 27, 2020 at 12:33AM by mariomxpx

Where can land free nodejs app hosting with free https?

Heroku wont let me even implement my own.And openShift is only for like 60 days.

Submitted May 26, 2020 at 03:36PM by paperruat

CPU-bound or I/O-bound approach with clustering in a high-stress environment?

Hi!I'm building a web app and we are facing major performance issues, and high CPU overload and stress.In this web app we use Express, Handlebars, Passport, Sequelize with MariaDB, node-redis with Redis and some others modules. We have an i9 9900K, 8 cores/16 threads, and we run pm2 cluster on 16 threads. That should be a powerful machine, but I don't know why there's some bottleneck which causes the CPU to get to 80%-90% or even 100% when 1000 or 2000 requests happen in like 50 seconds. Profiling can't help me, even StackOverflow can't, and I don't know how to handle it anymore, it's over 1 week that I'm trying to fix this CPU stress. Some people on StackOverflow agree with me that what my web app does is lots of data processing, but really simple and shouldn't be stressing this much the CPU.In the entire environment I have chosen to do this approach:Get data from Redis (or query it if doesn't exist) -> JSON.parse -> filter json array with Array.filter and other common array operations to get specific data.Now, we have to get very specific data and a lot of times, at least using those operations 10 times per request, on small or medium arrays of objects, from 6 entries up to 30k entries, hanging from Array.filter to Array.sort to Array.some and Array.find.This happens LOOOOTS of time, and we have to handle 3000 concurrent requests sometimes. This causes high CPU stress and latency, even if I managed to reduce a bit the event loop latency by inspecting it with blocked-at package. Also, looks like, from profiling, that a lot of processing is spent in garbage collecting. That looks like a memory leak.They always say that Node is I/O-bound and not CPU-bound due to event loop. So I thought this may not be the better approach to handle with this kind of data, and it would be better to avoid using lots of Array operations and just do SQL query which are I/O and not CPU.Is it right? Should I use more database queries and caching, instead of doing simple queries and handling large data with array operations? Won't lots of database queries stress my CPU anyway? Will it be better to do 3-4 non-cached queries each request or do 10-15 operations each request on cached queries?Thanks for helping and sorry for such a stupid question, probably, but really I don't know what to do anymore.

Submitted May 26, 2020 at 02:55PM by DanielVip3

Node v12.17.0 (LTS)

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

Submitted May 26, 2020 at 03:19PM by dwaxe

Deno | First Impressions

https://youtu.be/Olm9mpjy4Iw

Submitted May 26, 2020 at 02:23PM by coold007

Running simple node.js app on google app engine for free? Staging VS production

Trying to get a better understanding of google app engine...We just need to run an api there (node/apollo-server).Would be great to have a staging instance/app that only runs when we need it. I could manually turn it on and off myself but my understanding is I can setup the yaml to work this way... but I'm not sure exactly what the settings will be.Similarly, for production we don't need a lot of bandwidth. Given the below yaml, it's costing me about $1.45 a day... anyway to get it lower without having it go down to 0 instances (we don't have much traffic but I'd like it to not need to spin up when we do).​runtime: nodejsenv: flex# This sample incurs costs to run on the App Engine flexible environment.# The settings below are to reduce costs during testing and are not appropriate# for production use. For more information, see:# https://cloud.google.com/appengine/docs/flexible/nodejs/configuring-your-app-with-app-yamlmanual_scaling:instances: 1resources:cpu: 1memory_gb: 0.5disk_size_gb: 10I also have a semi-related question here: https://www.reddit.com/r/googlecloud/comments/gqvzt0/specifying_which_appyaml_to_deploy_with/

Submitted May 26, 2020 at 01:29PM by foundry41

Array not defined?

The error is that newArr is not defined. But when i console log i get the data that i need to. I tried having the update in the promise as well but still the same things..const SignUpForProject = (req, res) => { let dbContext = new DbContext().Initialize("projects"); let Parser = new FirebaseParser(); const token = req.cookies.token; let username; let newArr; if (!token) { res.render("Auth/Login", { error: "You need to be logged in to sing up!" }) } else { let payload = jwt.verify(token, 'auth') username = payload.username } let projectId = req.params.id let promise = dbContext.doc(projectId).get().then(snapshot => { let oldArrayFirebaseObj = snapshot["_fieldsProto"]["usersQueue"]["arrayValue"]["values"] newArr = Parser.ToArray(oldArrayFirebaseObj) newArr.push(username) console.log(newArr) console.log(newArr) }).catch( err => console.log(err) ) let data = { usersQueue: newArray } dbContext.doc(projectId).update(data, { merge: true }) }

Submitted May 26, 2020 at 01:05PM by draganov11

Why does this give me undefined?

const SignUpForProject = (req, res) =>{ let dbContext = new DbContext().Initialize("projects"); let projectId = req.params.id let promise = dbContext.doc(projectId).get().then(snapshot => { let oldArray = snapshot["_fieldsProto"]["usersQueue"]["values"] console.log(oldArray) }) //let data = {usersQueue: newArray} //let project = dbContext.doc(projectId).update(data,{merge: true}) res.end() } IM trying to get array from firebase document. I get other thing correctly but the array gives me undefined?

Submitted May 26, 2020 at 12:28PM by draganov11

Aren't you annoyed with Deploying Node.js applications on the server?

Hey, node.js developers!I am wondering does anybody has struggles when deploying your apps on the production server?I developed several web applications, and every time getting them running on the live server was a pain in the ass. Especially if the project consists of several micro-services.What you use for deploying your apps?So now I am working on my deployment automation app. It will let you deploy your node.js app in 3 minutes and a couple of clicks right from the git repo.I would appreciate hearing your expirience when deploying your apps.

Submitted May 26, 2020 at 12:24PM by vpilip

Why doesn't my test run my middleware with db.connect?

I have a middleware that I want to test and it contains a database connection.// register.js module.exports = (req, resp) => { db.connect((err, client, done) => { if (err) console.log(err); (async() => { try { await client.query('BEGIN') /* create user account */ await client.query('COMMIT') .then(() => { console.log('sending response'); resp.status(201).end(); }); } catch (e) { throw e; } finally { done(); } })() .catch(err => console.log(err)); }); } The test never reaches the console.log and there is no new row in my test database. Here is my test.describe('test registration', () => { it('will create a new account', (done) => { register(req, resp); // done(); }); }); I've tried using done after register() without result. I also notice the same problem when I use the request library to make a request to google recaptcha. Is there something I don't know about async operations like these?

Submitted May 26, 2020 at 12:11PM by eggtart_prince

How to Use FFmpeg to Fetch an Audio From Local Network and Decode it to PCM?

https://stackoverflow.com/questions/62006071/how-to-use-ffmpeg-to-fetch-an-audio-from-local-network-and-decode-it-to-pcm

Submitted May 26, 2020 at 11:08AM by yousifhood

Restrict access to a node.js API endpoint

I have a MERN stack web app and I'm attempting to restrict access to the API endpoints on the server. So only the frontend of my app can make these API requests. Is there a way of recognising whether an API request is coming from the frontend of my app, or from somebody running a curl command or another program like Postman creating the request?​Thanks in advance

Submitted May 26, 2020 at 10:24AM by eod97

Scalable image upload

Hello fellow nodes!I am building an image uploader and i'm looking for a scalable solution!Needs to resize into three different sizes on upload.Needs to be cheap.I'm thinking of the top of my head multer, sharp and s3 for storage.Any Ideas?

Submitted May 26, 2020 at 09:36AM by Doftgrahn

Video: Building a basic image classifier with Node.js, React, and Tensorflow

https://www.youtube.com/watch?v=ZfuUwdFNU-s

Submitted May 26, 2020 at 09:42AM by ttamimi

Map and Reduce — A Primer

https://medium.com//map-and-reduce-a-primer-9e18a6b7e587?source=friends_link&sk=118cf6710755f2190c0291c827ce340a

Submitted May 26, 2020 at 09:51AM by jsloverr

JavaScript CAD viewer Framwork

A little background information; We are currently busy building a WebApp which allows custom part ordering using 3D .stp/.step files. We are in need of a framework that supports 3d file viewing.I have already found frameworks like three.js, xeokit.io, and xeogl.I am curious if others have build a similair application and have recommendations. Feel free to discuss in the comments, am curious.​If you have any links or documents that I may have overlooked or you think it will add something to my search, please comment! Everything will be greatly appreciated!

Submitted May 26, 2020 at 08:57AM by tjallo

Hls ffmpeg conversion issues using child_process

Hey guys. I’m working on converting a live feed from a USB input to an hls stream and was having some issues. All the details can be found here but basically I keep getting a SIGABRT whenever I run a spawn command on a live feed (as opposed to a saved .mov file, for example).No clue why it’s happening but my child_process just wont seem to do what it’s told. Any ideas?

Submitted May 26, 2020 at 08:35AM by JeffLeafFan

How To Find The Best Node.js Developers For Your Team

http://selleoblog4.xyz

Submitted May 26, 2020 at 08:50AM by kingstonkerfuffle

Looking for advice on a web app implementation

Hi there, I am a beginner in Web Dev. I just finished a web dev Bootcamp so I want to do something to practice my skills.I have envisioned a website that can filter articles by the tags attached to each article. The filter would look similar to a hotel or flight booking website where there are checkboxes for each tag. On the right the first 5 articles satisfying the criteria will be displayed by default and if I scroll down more will get loaded. The articles displayed would refresh on the fly as the filter criteria changes.From the Bootcamp I have learned HTML, CSS, node.js, express, EJS and React. I have already prepared All the tags and article content in a MySQL database, and I am planning to deploy the website on Google App Engine (or anything free to get started).I guess this is not anything new, but I just want to finish it as a practice. However, I do not know where to get started. For example, I do not know if I should use node.js + express + EJS or to also include React in the project. I also do not know where to look for the sample code about the filter feature I just described. I tried GitHub but maybe I used the wrong keyword.If anyone has any idea please let me know! Much appreciated!

Submitted May 26, 2020 at 07:37AM by HunterTom94

Monday 25 May 2020

Data Model confusion

So have a few questions regarding data models that I am not quite sure about, and I apologize if this isn't the proper sub. But I will be giving two examples of 2 different User Models. One from a node-postgres back-end, and another from a node-mongoose back-end.​I am confused on a number of things:Is there a benefit to using an object to move data around (such as a model)? For example : Does it make it easier on the back-end and prevent mixing data up (like keeping a user's data consistently paired with their user_id or token) when the back-end starts to get bombarded with api calls? Does it help abstract data away even though I can easily see what is in a User object using console.log?Are they necessary? (In the bootcamp I attended they claimed that the models were good for abstraction and data hiding (specifically in the postgres model). However, to me, that seems trivial). Also, a few tutorials I have done use models, not with raw data.Why are both examples called models when they both clearly behave differently? Is there no set rule what defines a model?a). Are user models needed in the front end? To allow for comparability when sending information to the back-end? (Sending a user object to the front-end to the back-end to register the user). Or is that one of the reasons for data-abstraction-layers? (although I didn't think they were used anymore)b). If models are needed in the front-end, could someone see what dataparameters,and variable names, make up a user? (Like user_id). And could this be asecurity risk?​​tl;dr: If models are just objects holding associated data, whats the point?​Node-Postgres User Model Example:export class User{ userId=0; username=''; password=''; email=''; accountRoleId=0; token=''; constructor( userId?: number, username?: string, password?: string, email?: string, accountRoleId?: number, token?: string, ){ userId && (this.userId=userId); username && (this.username=username); password && (this.password=password); email && (this.email=email); accountRoleId && (this.accountRoleId=accountRoleId); token && (this.token=token); } } ​Node-Mongoose User Model Example:const mongoose = require('mongoose'); const bcrypt = require('bcrypt'); const jwt = require('jsonwebtoken'); const crypto = require('crypto'); const moment = require("moment"); const SALT_I = 10; require('dotenv').config(); const userSchema = mongoose.Schema({ email:{ type:String, required: true, trim: true, unique: 1 }, password:{ type:String, required: true, minlength: 5 }, name:{ type:String, required: true, maxlength:100 }, lastname:{ type:String, required: true, maxlength:100 }, cart:{ type:Array, default: [] }, history:{ type:Array, default: [] }, role:{ type:Number, default:0 }, token:{ type:String }, resetToken:{ type:String }, resetTokenExp:{ type:Number }, }); userSchema.pre('save',function(next){ var user = this; if(user.isModified('password')){ bcrypt.genSalt(SALT_I,function(err,salt){ if(err) return next(err); bcrypt.hash(user.password,salt,function(err,hash){ if(err) return next(err); user.password = hash; next(); }); }) } else{ next() } }) userSchema.methods.comparePassword = function(candidatePassword,cb){ bcrypt.compare(candidatePassword,this.password,function(err,isMatch){ if(err) return cb(err); cb(null,isMatch) }) } userSchema.methods.generateResetToken = function(cb){ var user = this; crypto.randomBytes(20,function(err,buffer){ var token = buffer.toString('hex'); var today = moment().startOf('day').valueOf(); var tomorrow = moment(today).endOf('day').valueOf(); user.resetToken = token; user.resetTokenExp = tomorrow; user.save(function(err,user){ if(err) return cb(err); cb(null,user); }) }) } userSchema.methods.generateToken = function(cb){ var user = this; var token = jwt.sign(user._id.toHexString(),process.env.SECRET) user.token = token; user.save(function(err,user){ if(err) return cb(err); cb(null,user); }) } userSchema.statics.findByToken = function(token,cb){ var user = this; jwt.verify(token,process.env.SECRET,function(err,decode){ user.findOne({"_id":decode,"token":token},function(err,user){ if(err) return cb(err); cb(null,user); }) }) } const User = mongoose.model('User',userSchema); module.exports = { User } ​tl;dr: If models are just objects holding associated data, whats the point?​​

Submitted May 26, 2020 at 06:44AM by bigbobbyboy5

NodeJS tutorials from scratch...

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

Submitted May 26, 2020 at 05:12AM by ukmsoft

API example using Firestore?

I've been working on getting a CRUD API using Firebase functions but I'm getting stuck on some if the updates to subcollections and I can't find any examples on how this is done. Anyone have any experience on this?

Submitted May 26, 2020 at 03:35AM by DAM9779

Activity feed using node and mongodb.

I'm looking for a push in the right direction... I have a node / react / mongo app I'm coding and was wanting to put together an activity feed. For example, "Bob created a new Todo List" or "New item added to Grocery List", etc. I wasn't sure if there was an easier path, but my initial thought was to create a logging table, and just add an entry for every specific tasks I want to log. But also thought I could write a script that just goes and collects what's changed in the database (related to the ToDo list in this example) and spit that out as something human readable. I'm curious if someone has some better insight into this before I get too deep and realise it's the wrong approach. Maybe an example app or node package that explores this?And maybe one more request... :)All of this was because I've been thinking of adding version control of sorts to my application. To allow users to undo a change. So, for this generic example, a user could scroll through an activity timeline and see all these changes to their Todo list. But could also revert back to a particular point of time. Another example would be gitbook. You can have a staging area of changes before you publish them. You can add to it and merge much like GIT would normally do. Any good leads or reads on how to approach this?Any help would be great!

Submitted May 26, 2020 at 03:06AM by thisisnots

Docs for Discord Bot with Machine Learning

Hello!After learning the basics of JavaScript/Node and Discord.JS, i had a idea to build a simple bot who read the messages in the server from a certain user, and begin to talk like them when mentioned.Is there any good tutorial/documentation about how to make a AI learning chatbot?I tried to follow a Twitter "impersonator" repository posted on The Guardian but the code didnt have a single comment line to guide myself ( a noob, i know).

Submitted May 26, 2020 at 01:39AM by the_vico

What is Node.js ? Need help.

HiI see this node.js thing running in my task manager but I'm wondering what it does.Someone has threatened me to put a keylogger on my pc and steal passwords or something. Could it be used as a keylogger?Is node.js standard on windows10? Pls explain as I'm not a techdude.

Submitted May 25, 2020 at 09:32PM by OfficialVex

Building Free Website Availability Monitoring App using Google Cloud

https://youtu.be/IN2h_O6GdUc

Submitted May 25, 2020 at 05:43PM by TomekB

Is it good to have “error driven actions” ?

Is it good practice to have actions in app witch may activate from backend error function?For example there is an api for creating order, all users must have email to create order, is it good to return some error { error: {code:55//missing email}}and app will open page where user must enter email or to have some api for user profile check and return regular error from backend if profile is not completed?

Submitted May 25, 2020 at 04:57PM by Grigsuv

Sessions in Node #5 | Authentication in Node.js with Express and sessions | refactoring codebase

https://youtu.be/qzKRzwZzc6o

Submitted May 25, 2020 at 04:33PM by prodcoder

API with NestJS #3. Authenticating users with bcrypt, Passport, JWT, and cookies

https://wanago.io/2020/05/25/api-nestjs-authenticating-users-bcrypt-passport-jwt-cookies/

Submitted May 25, 2020 at 02:38PM by _gnx

node newbie

Hi guys,I'm super new to node.jshave set up a preliminary dev environment with VS code, mongodb and node js.Current challenge: I've been struggling to upload a single document from a basic html input element to a localhost with my week to two of knowledge in javascript.Have some VBA projects under my belt so I understand the basic concepts of programming - but for anyone out there who has found a resource that helped them with a similar project or just to grasp node.js from the get go, any pointers would be much appreciated!

Submitted May 25, 2020 at 01:28PM by Ardinius

How do I show the same webpage to all computers connected on my local node.js server ?

So basically when you connect to my local server, it shows the login page and the webpages later right ?So what I want to do is that when every computer has clicked on a certain button , every computer currently connected to my webpage should start showing the same html page , without refresh or anything.Is this possible ?

Submitted May 25, 2020 at 01:34PM by psaiko_dro

Using mLab vs creating own database

I'm wondering what are the downsides of hosting my own MongoDB database on e.g. Digital Ocean (which is much cheaper) vs using mLab.Thanks

Submitted May 25, 2020 at 09:44AM by everek123

Quality of posts/tutorials online

I’ve been seeing most of articles/tutorials written online about not just node but programming related content is made by people who do not have deep understanding of the subjects and make basic introductory posts about the subject purely just to make content rather spreading knowledge. I feel as though most of the tutorials/articles or even courses such as udemy have no extensive knowledge about the topic is made by people who are learning themselves, students or junior devs who don’t really know what they’re doing

Submitted May 25, 2020 at 09:22AM by onredditcuzwhynot

Dont you think Node is a kind of philosophy which should be adopted in software engineering process

Put yourselves into shoes of a Head Technical Manager . Imagine your teammates a hard working worker thread.If you really wanna deliver things quickly, what you gonna do ?You would like to put all your workers busy at every moment.Imagine if some teammates are dependent on each other , this would terribly halt the progress, which I suppose no one would like.Switch to node , where every worker works asynchronously.This would surely enhance the output in optimised time duration.Ohh, wait what if we start adopting the technical philosophy like that of Node and any other topic.Dont you think it would mark the end of human and beginning of machine era. Or rather , are we already on this path . I dont know , this rather makes me think mad.I would hope that we could train machines to be more of a human and humans more to be machine.Thanks !

Submitted May 25, 2020 at 08:32AM by invertedme

Sunday 24 May 2020

What is/was `yinst`?

I recently found myself reading over the old npm FAQ (it was removed several years ago; see #10547 and came across the following section:If 'npm' is an acronym, why is it never capitalized?Contrary to the belief of many, "npm" is not in fact an abbreviation for "Node Package Manager". It is a recursive bacronymic abbreviation for "npm is not an acronym". (If it was "ninaa", then it would be an acronym, and thus incorrectly named.)"NPM", however, is an acronym (more precisely, a capitonym) for the National Association of Pastoral Musicians. You can learn more about them at http://npm.org/.In software, "NPM" is a Non-Parametric Mapping utility written by Chris Rorden. You can analyze pictures of brains with it. Learn more about the (capitalized) NPM program at http://www.cabiatl.com/mricro/npm/.The first seed that eventually grew into this flower was a bash utility named "pm", which was a shortened descendent of "pkgmakeinst", a bash function that was used to install various different things on different platforms, most often using Yahoo's yinst. If npm was ever an acronym for anything, it was node pm or maybe new pm.So, in all seriousness, the "npm" project is named after its command-line utility, which was organically selected to be easily typed by a right-handed programmer using a US QWERTY keyboard layout, ending with the right-ring-finger in a postition to type the - key for flags and other command-line arguments. That command-line utility is always lower-case, though it starts most sentences it is a part of.According to the fourth paragraph, there is/was a utility named yinst somewhere out there. What is/was it and what's the story behind it?

Submitted May 25, 2020 at 06:29AM by mjbmitch

Express-session help? Cookie maxAge resets on each refresh/request

Hey guys. First post here, really hoping I can get some help. I've spent about 4 hours googling this to try and find some sort of solution that works. Nothing is helping. I'm using express and express-sessions.I'm just trying to make a cookie that expires in 5 seconds and have the time left of the cookie display on a page. The problem is, every single time I refresh the page, the cookie life resets. This shouldn't be happening.Here's my code (leaving some unrelated stuff out)index.jsconst express = require("express"); const app = express(); const path = require("path"); const expbs = require("express-handlebars"); const session = require("express-session"); ... app.use(session({ secret: "test session signature", resave: false, saveUninitialized: false, rolling: false, cookie: { maxAge: 5000 } })); ... app.get("/", (req,res)=>{ if(req.session.views){ req.session.views++; // set handlebars variables to display the cookie life and view count res.locals.testViews = req.session.views; res.locals.testExpire = req.session.cookie.maxAge; } else { req.session.views = 1; } res.render("index", homeData); }); I've already tried several combinations of the resave, savuninitialized, and rolling parameters. No matter what combination I choose, the maxAge gets reset on each page request.What the hell is going on?

Submitted May 25, 2020 at 06:01AM by cuboidofficial

Is typescript useful for developing nodejs backend?

I'm not a frontend dev but I have been using jquery with some vanilla js for some frontend work. I see people talk much about how good is typescript. But is it really useful for the backend part?

Submitted May 25, 2020 at 05:44AM by pverma8172

First steps with Bosque - Part 2

https://blog.brakmic.com/first-steps-with-bosque-part-2/

Submitted May 25, 2020 at 12:45AM by brakmic

cheerio keeps giving me null values

hello everyone i'm learnign web scraping with cheerio and i'm trying my best i have been learning it for two days and some sites work with it and some not i tried using it with some complex sites but it keeps giving me null and i need your help with itconst cheerio = require('cheerio');const request = require('request');function getData() {request('https://www.starbucks.com/menu/drinks/hot-coffees', (err, res, html) => {const $ = cheerio.load(html)const lattes = $('.undefinde')console.log(lattes.html())    })}getData()i tried to use the same methode with covid-19 sites and it worked fine

Submitted May 24, 2020 at 08:34PM by Tom-Wildston

[WIP] src,lib: policy permissions by jasnell · Pull Request #33504 · nodejs/node · GitHub

https://github.com/nodejs/node/pull/33504

Submitted May 24, 2020 at 07:41PM by sectruth

Word here for beginner guys

I'm new to javascript ,I just had some html ,css.so I want any best video tutorial from anywhere and any articles for my improvement and books alsoA suggestion guys what should I do after js like angular or nodejs or mongodb or react or your choice alsoI khow there are many post regarding these but they all doesn't have video link to it and all messed up little😋

Submitted May 24, 2020 at 07:41PM by VkrajaP

How do i make jwt cookie never expire?

I have login set with jwt and cookie i set up the expiry in 2 hours and every two hours i get the error view with error jwt expired how can i either make it never to expire or handle when it expires?Here is my auth controller what do i change?​const PostRegister = async (req, res) => { let dbContext = new DbContext().Initialize("users"); let authService = new AuthService(); let { Username, Email, Password } = req.body; let toReturn = false; var counter = 0; let promise = dbContext.where("email", "==", Email).limit(1).get() .then((user) => { user.forEach(() => { counter++; }) }) .catch(() => { }) .finally(() => { console.log(counter); if (counter !== 0) { console.log(`${Username} , ${Email} , ${Password}`); res.render("Auth/Register", { error: "Email already exists!" }) return res.end(); } else if (Password.length < 4) { res.render("Auth/Register", { error: "Password too small!" }) return res.end(); } else { let user = new User(Username, Email, Password, new Date()); authService.SaveUser(user); res.redirect("/"); res.end() } }); } const PostLogin = (req, res) => { let dbContext = new DbContext().Initialize("users"); let authService = new AuthService(); let { Username, Password } = req.body; let counter = 0; let querry = dbContext.where('username', '==', Username).limit(1); let username; let admin; let password; querry.get() .then((document) => { document.forEach((user) => { username = user['_fieldsProto']['username']['stringValue']; admin = user['_fieldsProto']['isAdmin']['booleanValue']; password = user['_fieldsProto']['password']['stringValue']; counter++; }) if (counter === 0) { res.render("Auth/Register", { error: 'User does not exist!' }); res.end(); } }) .finally((document) => { bcript.compare(Password, password, (err, response) => { if (!response) { res.render("Auth/Login", { error: 'Wrong password!' }); res.end(); } else { const expirySec = 30000; console.log(response) console.log(Password) let token = authService.JWTAuthenticate({ username, admin }, expirySec, jwtKey); res.cookie("token", token, { maxAge: expirySec * 1000000 }) res.redirect("/") res.end(); } }); }) } const Logout = (req, res) => { res.clearCookie("token"); res.redirect('/Auth/Login') res.end(); } const SendResetEmail = (req, res) => { let dbContext = new DbContext().Initialize("users"); let { Email } = req.body; let querry = dbContext.where('email', '==', Email); querry.get() .then((document) => { if (!document) { res.render("Auth/ResetPass", { error: "Email dosent exist!" }); res.end(); } else { let mailer = new Mailer(); let code; document.forEach((user) => { code = user['_fieldsProto']['key']['stringValue']; }) mailer.SendEmail(Email, code, "DevSpaceR password reset code"); res.render("Auth/ResetPass", { error: "Email sent!" }); res.end(); } }) } const PostResetPassword = (req, res) => { let { Code, NewPassword, Email } = req.body; let dbContext = new DbContext().Initialize("users"); let dbCode; let querry = dbContext.where('email', '==', Email); bcript.hash(NewPassword, 12, (err, hash) => { querry.get() .then((document) => { if (!document) { res.render("Auth/ResetPass", { error: "Email dosent exist!" }); res.end(); } else { document.forEach((user) => { const id = user.id; dbCode = user['_fieldsProto']['key']['stringValue']; if (dbCode !== Code) { console.log(dbCode) res.render("Auth/ResetPass", { error: "Wrong key!" }) res.end() } else if (NewPassword.length < 4) { res.render("Auth/ResetPass", { error: "Password too small!" }) return res.end(); } else { let newKey = KeyGenerate(9, 0) dbContext.doc(id).update({ password: hash }); dbContext.doc(id).update({ key: newKey }); res.render("Auth/ResetPass", { error: "Password changed!" }) res.end() } }) } }) }) } module.exports = { GetRegister, GetLogin, GetResetPassword, PostRegister, PostLogin, PostResetPassword, Logout, SendResetEmail }

Submitted May 24, 2020 at 07:31PM by draganov11

Want to create blog writing CMS for my existing website need guidance or some helpful links

Basically i have a static website and i want to make cms for writing blogs, it is developed using node.js. My idea is basically anyone Should be able to create account and start posting blogs similar to that of wordpress. Not necessarily drag and drop but something that can help write blog. Any api,library links tutorials or anything else would be of great help.

Submitted May 24, 2020 at 07:32PM by prathameshbhat

Getting error based on where I place my route

HiI'm getting a weird error with one of my routes on my express app. I have a list routesrouter.get('/property', catchErrors(propertyController.getAllProperty)); router.get('/property/:id', catchErrors(propertyController.getProperty)); router.get('/property/add/', propertyController.addProperty); router.post('/property', catchErrors(propertyController.createProperty)); router.get('/property/edit', propertyController.editProperty); router.put('/property/:id', catchErrors(propertyController.updateProperty)); router.delete('/property/:id', catchErrors(propertyController.deleteProperty));When I hit the following route `/property/add/`, I get the following error `Cast to ObjectId failed for value "add" at path "_id" for model "Property"`.All I'm trying to do is render out a simple json placeholder like thisexports.addProperty = (req, res) => {res.json('Form for adding new property');};However if I move the route above the rest, it works as expected. Any ideas?

Submitted May 24, 2020 at 07:33PM by Deviso

Can i get code review on my authentication and how can i do it better?

I have it working but i think i can do much better code wise i just cant think of how. What should i change/add to make it better?const PostRegister = async (req, res) => { let dbContext = new DbContext().Initialize("users"); let authService = new AuthService(); let { Username, Email, Password } = req.body; let toReturn = false; var counter = 0; let promise = dbContext.where("email", "==", Email).limit(1).get() .then((user) => { user.forEach(() => { counter++; }) }) .catch(() => { }) .finally(() => { console.log(counter); if (counter !== 0) { console.log(`${Username} , ${Email} , ${Password}`); res.render("Auth/Register", { error: "Email already exists!" }) return res.end(); } else if (Password.length < 4) { res.render("Auth/Register", { error: "Password too small!" }) return res.end(); } else { let user = new User(Username, Email, Password, new Date()); authService.SaveUser(user); res.redirect("/"); res.end() } }); } const PostLogin = (req, res) => { let dbContext = new DbContext().Initialize("users"); let authService = new AuthService(); let { Username, Password } = req.body; let counter = 0; let querry = dbContext.where('username', '==', Username).limit(1); let username; let admin; let password; querry.get() .then((document) => { document.forEach((user) => { username = user['_fieldsProto']['username']['stringValue']; admin = user['_fieldsProto']['isAdmin']['booleanValue']; password = user['_fieldsProto']['password']['stringValue']; counter++; }) if (counter === 0) { res.render("Auth/Register", { error: 'User does not exist!' }); res.end(); } }) .finally((document) => { bcript.compare(Password, password, (err, response) => { if (!response) { res.render("Auth/Login", { error: 'Wrong password!' }); res.end(); } else { const expirySec = 30000; console.log(response) console.log(Password) let token = authService.JWTAuthenticate({ username, admin }, expirySec, jwtKey); res.cookie("token", token, { maxAge: expirySec * 1000000 }) res.redirect("/") res.end(); } }); }) } const Logout = (req, res) => { res.clearCookie("token"); res.redirect('/Auth/Login') res.end(); } const SendResetEmail = (req, res) => { let dbContext = new DbContext().Initialize("users"); let { Email } = req.body; let querry = dbContext.where('email', '==', Email); querry.get() .then((document) => { if (!document) { res.render("Auth/ResetPass", { error: "Email dosent exist!" }); res.end(); } else { let mailer = new Mailer(); let code; document.forEach((user) => { code = user['_fieldsProto']['key']['stringValue']; }) mailer.SendEmail(Email, code, "DevSpaceR password reset code"); res.render("Auth/ResetPass", { error: "Email sent!" }); res.end(); } }) } const PostResetPassword = (req, res) => { let { Code, NewPassword, Email } = req.body; let dbContext = new DbContext().Initialize("users"); let dbCode; let querry = dbContext.where('email', '==', Email); bcript.hash(NewPassword, 12, (err, hash) => { querry.get() .then((document) => { if (!document) { res.render("Auth/ResetPass", { error: "Email dosent exist!" }); res.end(); } else { document.forEach((user) => { const id = user.id; dbCode = user['_fieldsProto']['key']['stringValue']; if (dbCode !== Code) { console.log(dbCode) res.render("Auth/ResetPass", { error: "Wrong key!" }) res.end() } else if (NewPassword.length < 4) { res.render("Auth/ResetPass", { error: "Password too small!" }) return res.end(); } else { let newKey = KeyGenerate(9, 0) dbContext.doc(id).update({ password: hash }); dbContext.doc(id).update({ key: newKey }); res.render("Auth/ResetPass", { error: "Password changed!" }) res.end() } }) } }) }) } module.exports = { GetRegister, GetLogin, GetResetPassword, PostRegister, PostLogin, PostResetPassword, Logout, SendResetEmail }

Submitted May 24, 2020 at 07:33PM by draganov11

Humble Book Bundle: Definitive Guides to All Things Programming by O'Reilly (pay what you want and help charity)

https://www.humblebundle.com/books/definitive-guides-to-all-things-programming-oreilly-books?partner=repsup

Submitted May 24, 2020 at 07:15PM by big_clips

All user's get their own frontend, but do all users share the same backend?

Let me explain. So I understand that when a user goes to my website my react/html pages/vue frontend is loaded into their browser, and they can do whatever they want with it. It is theirs. And when another user goes to my site, they get the frontend loaded into their browser. That one is theirs. And every user that goes to my site, gets their own frontend that they can do whatever they want with.But if one user does something and sends a request to my backend, couldn't another user be using the same function (or api) as them, at the same time, causing a block?Is there only one server that every user is using simultaneously? Or is there a new instance of a server made for every browser/user?Or is this why proxy serves and load balancers are so important? (To create new server instances)

Submitted May 24, 2020 at 06:51PM by bigbobbyboy5

Why you should use nestjs

https://www.youtube.com/watch?v=g3qX9eQSog4&list=PLIGDNOJWiL18KaYJnBXDCqf8C2tW-nURD

Submitted May 24, 2020 at 05:15PM by tkssharma

Nodejs Deployment

Hello,I am a new nodejs developer, and in the past I got a way with heroku PAAS as a deployment platform for my toy apps. Rightnow, I need to deploy a real project. What service provider do you recommend interns of documentation, community support, compatibility with node)express? Most of the tutorials are about digital Ocean, but I also heard they're getting worse now.

Submitted May 24, 2020 at 04:41PM by ZYusuf