Thursday 30 April 2020

How to Schedule Cron Jobs and Set Health Checks in Node.js

https://medium.com/@pkoulianos/how-to-schedule-cron-jobs-and-set-health-checks-in-node-js-93cf88d2c247

Submitted May 01, 2020 at 06:30AM by pkoulianos

Please how do I best handle authentication in multiple micro-service?

For example, I have a user micro-service and a product micro-service. User micro-service creates a token on login. How do I handle authentication in the product micro-service.

Submitted May 01, 2020 at 06:51AM by dudewith3faces

Rust and Node.js: A match made in heaven - LogRocket Blog

https://blog.logrocket.com/rust-and-node-js-a-match-made-in-heaven/

Submitted April 30, 2020 at 11:03PM by pmz

I need help with storing user input in a server-side nedb database

Hello There!Soo.. here is my Problem. I want to store User input on a Server-Side nedb database but dont know how.. Im pretty new so.. dont blame me 😅Im runing an Apache Server on a Ubuntu Machine.I know that nedb is a node libary, so I use browserify to use it with js..On my Website is a username form and a Button, and i want to Store the username onclick in the database.. is there any way to do that? (Tried it with fetch but I didnt understand anything.)Thank you really much for your help!

Submitted May 01, 2020 at 03:16AM by Pengster123

Any good tutorials on Rabbit MQ, Hadoop and Sharding in a Node.js environment?

Any good tutorials on Rabbit MQ, Hadoop and Sharding in a Node.js environment? Looked at some job posting recently and I found those requirements. Interested to see if there's a good practical tutorial.

Submitted May 01, 2020 at 02:59AM by jasonscript

Read data in real time from API service... ?

Hello everyone,​I'm currently developping I'm currently developing an application which reads JSON data from an API web service and stores it in a database, now all the data is read using 'node-fetch' module and 'node-schedule' which reads data every minute, but relying on this method produces a lag of 10 seconds because it reads data every minute even if it catches new data or not.​At this point, I'd like to know if I can make use of socket.io and 'wait' for the API service to update the data array when it's released instead of reading it every minute?

Submitted April 30, 2020 at 10:04PM by condrove10

How to use HTML frontend and Node.js backend?

I have a website that I’ve hosted through my university. I want that website to be able to display the data when given a website link. For example, if I were to press submit in the HTML frontend, then will send a url to the Node.js backend which scrapes the website for text. The Node.js will then display that data onto the HTML page I’m hosting. How can I go about accomplishing this?

Submitted April 30, 2020 at 11:40PM by robinbatman1966

Does anyone else have to deal with monetizing npm libraries?

No text found

Submitted April 30, 2020 at 08:27PM by Mesthabro

[help] i'm trying to store into mongoDB infos from reddit 'API' but i can't get past first results!

hello everybody!i'm trying to learn some nodejs, and i was trying to store into a mongoDB (a free atlas cluster), data from reddit.the data that i'm getting is from https://www.reddit.com/r/pics/top.json?t=weekto go to the next page i can add to the end of the link &after= plus the info that i get from the json itself (it's an alphanumeric string, like t3_gaea5j. i want to cycle and get as many results as i want, but after the first result the data that i pull out is always the same.this is the promise that i use to get the json const redditjson = new Promise((resolve,reject)=>{ i++; json = ''; let parsed =''; console.log(); //var options = new URL('https://www.reddit.com/r/pics/top.json?t=weer next=' r next); https.get(url, (resp) => { resp.on('data', (chunk) => { json += chunk; resp.on('end', () => { parsed = JSON.parse(json); next = parsed.data.after; return resolve (parsed); }); }); }); and this is the function that i use to fetch what i needasync function connect() { app.listen(3000, () => { MongoClient.connect(CONNECTION_URL, { useNewUrlParser: true }, (error, client) => { if (error) { throw error; } database = client.db(DATABASE_NAME); collection = database.collection("pic"); console.log("Connected to " + DATABASE_NAME + "`!"); // upload(redditjson); for (let index = 0; index < 3; index++) { redditjson.then(result=> { console.log(index); console.log(next); next = result.data.after; url = ('https://www.reddit.com/r/pics/top.json?t=week&after=' + next); result.data.children.forEach(element => { redditObj = { 'upvote': element.data.ups, 'subreddit': element.data.subreddit, 'utcPost': element.data.created_utc, 'link': element.data.permalink, 'title': element.data.title, 'type': element.data.post_hint }; console.log(redditObj); arrObj.push(redditObj); }); //upload(arrObj, collection); redditObj = []; arrObj={}; }); } }); }); } code is a little bit messy because i tried a lot of things before coming to ask here, so sorry if it doesn't make any sense to you!things that i tried so far :- eventHandler-promises-calling what's inside the promise as a function inside connect();-tried without async functionsthe first time loop it works, at the second one it just breaks, and gives me back nothing.thanks to everyone who wants to help someone who wants to learn nodejs!

Submitted April 30, 2020 at 08:02PM by christmas_fighters

Just Finished My First Ever Node Js Program: A Home Backup and Transfer Server.

https://v.redd.it/qx9643rnozv41

Submitted April 30, 2020 at 06:22PM by -EliTheNut-

The Mobile Version of My Node Js Server

https://v.redd.it/e7y1frbwozv41

Submitted April 30, 2020 at 06:23PM by -EliTheNut-

Does anyone know any node module that merges pdfs without destroying their index but also allows to add the pdf names as new parent index?

Lets say that I have some pdf files . Dome of them have index , some dont . I want a node module that allows me to merge pdfs without destroying their index but also adding the pdf name as the parent index . Do such a node module exist?

Submitted April 30, 2020 at 05:38PM by liaguris

Smart Light Widget

https://v.redd.it/8j54xkdp42v41

Submitted April 30, 2020 at 04:45PM by codeherk

shargs (shell args) is a library for building next-generation command-line arguments parsers

https://github.com/Yord/shargs

Submitted April 30, 2020 at 04:52PM by Yord13

Node v13.14.0 (Current)

https://nodejs.org/en/blog/release/v13.14.0/

Submitted April 30, 2020 at 03:56PM by dwaxe

Configuring winston logger

Hi, I need some help configuring winston, would be cool if you could have a look at this: https://stackoverflow.com/questions/61525425/configuring-winston-logger

Submitted April 30, 2020 at 03:29PM by StoryOfStella

I need to build a Webapp with a e-commerce store backend - where to start?

/r/reactjs/comments/gavs4s/i_need_to_build_a_webapp_with_a_ecommerce_store/

Submitted April 30, 2020 at 02:39PM by hello_krittie

Best way to cleanly remove NPM installs from project?

I am doing a project in react and was using Yarn for my package management. I accidentally ran NPM install the other day out of habit and am just realizing this now. What is the best practice for removing the NPM installs? Is it as simple as removing the package-lock.json?

Submitted April 30, 2020 at 02:23PM by Tennysonn

Objection.js - How to handle update, delete, ... queries better in Express with MySQL as the database?

Whenever a delete, update,... query is made in Objection using the MySQL database, the query only returns affected rows, but not the affected data.In Express, my current approach would be to make if/else statements on a function level, like the one below: js router.delete("/", async (req, res, next) => { const { id } = req.body; try { const todo = await Todo.query().deleteById(id); // deleteById returns the affected rows; if delete was successful, returns value 1 if (todo) { res.json({ message: "Item successfully deleted" }); } else { res.json({ message: "Item not found" }); } } catch (err) { next(err); } });However, this if/else approach inside a function doesn't seem right to me. What if multiple developers work on the same project and each one of them returns messages with different meanings or information.Does anyone have a suggestion or maybe even a repository that handles this better?

Submitted April 30, 2020 at 02:04PM by Tanckom

i18n-cloud-sync easily store your i18n strings in the cloud

TLDR; https://github.com/EvanBurbidge/i18n-sync-example < example usage of this project.i18n-cloud-sync is a simple project that provides a restful api for syncing translations, and their locations to the cloud. All work is done via restful api calls in order to update files and configurations.Currently it supportsS3Digital ocean spacesAzureGoogle StorageIt's available as both an npm package and as a docker image. You can choose how to run it.For more information you can check out the repo here :)https://github.com/EvanBurbidge/i18n-cloud-sync#readme

Submitted April 30, 2020 at 01:55PM by TheWebUiGuy

how to create better db structure?

Hello Programmers,whenever i read through the project statement while developing backend api, i have very hard time designing relationships, schema, etc. basically the structure of my db.Can someone please suggest me a good article / course / blogpost / skill which i should have so that i can create better db designs.

Submitted April 30, 2020 at 11:48AM by meMindFlayer

Ideas for a new npm package

Hello makersWhat are some problems that you face during backend development and believe that a npm package for the same can fix them up ?

Submitted April 30, 2020 at 10:08AM by amitbh

How to change value of object attribute which is inside an array using JavaScript

state = { todos:[ {id:1, title: 'Eat breakfast', completed: false}, {id:2, title: 'Make bed', completed: false} ] }; if my id==-3 then update title = 'dinner' if my id != 3 then don't updatehow can i do this?

Submitted April 30, 2020 at 10:51AM by mtkxvx

OAuth and session management - Do you know the difference?🤔 Make sure you’re implementing user authentication correctly.

OAuth 2.0 vs Session Management

Submitted April 30, 2020 at 09:23AM by saif_sadiq

Building Social Media Using Strapi JS

Hello there, sorry if this question is posted in the wrong subreddit. I've been reading Strapi JS, it seems like it is a good CMS for blogs etc. I'm wondering if I can use Strapi JS to build a social media platform as the backend api. Is it possible to do so? Or would I be fighting with the framework just to get the exact detail that I want?

Submitted April 30, 2020 at 08:23AM by snbn

Suggestions regarding node-cron.

My scenario:We have many usersI am am planning to use node-cron: https://www.npmjs.com/package/node-cronThese users have 'invoice periods', invoice data for each users should be entered in database based on their individual 'invoice periods'for eg user-1 has 7 days invoice period, user-2 has 30 days invoice periodwe will need 2 cron jobs to accomplish theseI am using adonisjsSince these cron jobs must be initialized as soon as the server starts, may be they should be placed in the entry point of the server i.e index js but this doesnt sound good practiceMy question is where should this function be placed within the code base, again, its an adonisjs system

Submitted April 30, 2020 at 07:21AM by ajirnanashak

Migrating from Promise chains to Async/Await

https://afteracademy.com/blog/migrating-from-promise-chains-to-async-await

Submitted April 30, 2020 at 07:47AM by janishar

Wednesday 29 April 2020

getting {} as response to http req due to bad associations

I have two tables://User.js module.exports = (sequelize, DataTypes) => { const User = sequelize.define("User", { userId: { type: DataTypes.STRING, allowNull: false, unique: true, primaryKey: true, }, email: { type: DataTypes.STRING, }, firstName: { type: DataTypes.STRING, allowNull: false, }, lastName: { type: DataTypes.STRING, defaultValue: "", }, password: { type: DataTypes.STRING, allowNull: false, }, chapterId: { type: DataTypes.STRING, }, }); User.associate = (models) => { User.belongsTo(models.Chapter, { foreignKey: "chapterId", targetKey: "chapterId", as: "chapter", }); }; return User; }; and//chapter table module.exports = (sequelize, DataTypes) => { const Chapter = sequelize.define("Chapter", { chapterId: { type: DataTypes.STRING, allowNull: false, unique: true, primaryKey: true, }, chapterName: { type: DataTypes.STRING, allowNull: false, }, isChapterLocal: { type: DataTypes.BOOLEAN, allowNull: false, }, }); Chapter.associate = (models) => { }; return Chapter; }; and i am trying to fetch users with chapters included into it based on chapterId.let getAll = async (req, res) => { try { const userData = await db.User.findAll({ include: [ { model: Chapter, as: "chapter", }, ], }); res.send(userData); } catch (e) { res.send(e); } }; feels like my associations are the problem.how to include chapter id and chapter name from chapter table, as present in chapterId row for user table. I am new to sequelize and MySQL and am unsure if the relation i have defined in the user model is good. Do we need to define associations in both tables.HELP!!

Submitted April 30, 2020 at 06:07AM by meMindFlayer

Angular, JavaScript, NodeJS, Html5, CSS3 quick Concepts...

https://www.tutorialslogic.com/angular?n.g.9.0

Submitted April 30, 2020 at 04:30AM by divya1994

Creating RESTful APIs using Node.js

https://link.medium.com/wsKwYbLe55

Submitted April 29, 2020 at 05:10PM by JeyK333

Distributed transactions are Not Micro-services

https://www.talentica.com/blogs/distributed-transactions-are-not-micro-services/

Submitted April 29, 2020 at 05:15PM by ratneshsinghparihar

XERN dockerized

Hi, im just finished an idea for deploy an development enviroment with docker, and i want to you could check it out for some feedback​This enviroment has some features like:​Backend.- Express with typescript.- Bull for Queue Jobs.- Socket.io for websocket.- TypeORM and mongoose for database services (you can between switch services or use both at same time).- Scraping data with cheerio.- Auth and Authz with jwt​Frontend.- React, Redux.- Formik for form validation.- Some css with styled-components and bootstrap​Docker-compose.- Microservices oriented backend services (main app, websocket, queue jobs).- Custom entrypoint for every backend service.- Nginx proxy container for api and websocket requests and some security settings​here is the repo https://github.com/alenq1/XERN-Dockerizedthanks

Submitted April 29, 2020 at 04:51PM by jandroenq

Chrome requesting download route twice on iOS?

Hello all, recently I’ve been running into an issue getting file downloading working on iOS. It seems like specially for Chrome/Firefox on iOS, the device requests the download route twice, once before the user clicks the ‘download’ prompt, and once again after the user presses it. This is not a problem on Safari for iOS, and it breaks the authentication for my download routes.I did make a demo: https://github.com/subnub/ios-chrome-download-exampleYou’ll notice in the demo that if you use Chrome or Firefox on iOS it requests the download route twice, not only that it will serve up all the bytes of the first request, and just discard all of them. But, if you use Safari, it will only make the download request once like it should.Any advice would be greatly appreciated, I’ve been stuck on this for some time now.

Submitted April 29, 2020 at 04:58PM by subnub99

Daemon/Processes Architecture?

I'm building some backend daemons that effectively just continuously run and process new data, or respond to events.​Right now I'm simply managing this with a task that I run every n milliseconds via setTimeout/setInterval. The task wakes up, runs once, then waits for it to be woken up again.This works and I can do a few things to make it more resilient on my own, but was wondering if there was some framework, or library that has already solved and abstracted away this problem.I'm not looking for a jobs queue/manager. I'm looking more for something like express for backend data processes.Any suggestions?

Submitted April 29, 2020 at 02:59PM by 4_teh_lulz

How to manipulate images like snapfish.com

I would like to create a site like https://www.snapfish.com/ where I can edit images on the fly. I will be using React.js in the frontend and Node.Js on the backend. Now, the question is, how do I manipulate the images on the fly? Like, add filters, color correction, and cropping. Do I do them at the frontend or at the backend? What options are available for image manipulation?

Submitted April 29, 2020 at 12:35PM by ShovonX

Module for web scraping JS-rendered data that can run in a browser?

Hi, I'm currently making a Chrome Extension and need a tool that can run in a browser and scrape JS-rendered data. Been trying to get Puppeteer to work but it seems that they deprecated that functionality at some point, all the links I've found to getting it working in a browser have been a dead-end.Thanks!

Submitted April 29, 2020 at 11:49AM by yesdefinitely_

How to listen for updates on multiple twitter accounts using Twitter Account Activity API??

/r/Twitter/comments/ga7cs2/how_to_listen_for_updates_on_multiple_twitter/

Submitted April 29, 2020 at 11:59AM by yashatreya

Problems with uploading image with axios

Here is the problem: https://stackoverflow.com/questions/61408006/getting-req-body-and-req-file-as-empty-when-uploading-file-with-axios

Submitted April 29, 2020 at 10:30AM by kamranibrahimov

Why does this promise not return a value but pending?

async EmailExist(email) { let dbContext = new DbContext().Initialize("users"); let toReturn =false; let counter = 0; let promise = dbContext.where("email", "==", email).limit(1).get() .then((user) => { user.forEach(() => { counter++; }) }) .finally(() => { console.log(counter); if(counter !== 0){ return true; } else{ return false; } }); return await promise; } I need to check if email exists with firebase i limit the querry to 1 and if there is 1 user with that email i increase a counter i check if the counter is 1 and if it is i return a bool value that i use in my controller. Problem is when i log the methid i get promise pending not the value i want to return i tried with or withou await asyn i tried returning the value and changing it in the promise then but the change dosent register. It works when i log the counter in the promise but i cant return anything good to use in the controller.

Submitted April 29, 2020 at 09:42AM by draganov11

Elasticsearch tutorial – how to get started and properly use it?

Hi everybody! If you need a super-fast and easy full-text searching tool, I’ve written an Elasticsearch tutorial for beginners. It’s an open-source tool from the Elastic roster. Recently, I’ve had multiple occasions to try out this solution in my projects and I must say it works pretty well in Node.js. Since I found it quite convenient, I thought that somebody else might be looking around for a similar solution and needing a little help with setting it up. I’m also quite interested in what kind of tools for browsing bottomless pits of data do you use that work well for Node developers? I’m quite happy with Elasticsearch but I’ll gladly check out your recommendations.

Submitted April 29, 2020 at 10:29AM by mgce_

can we pull off a node backend project with using migrations??

I started my project with sequeliz-cli by running init command.but i deleted the migrations and seeder folder. and started creating the models.I need to first create a db in workbench, and then ran db.sync() from sequelize, which created the tables in db. Its running kind of fine.can we complete the whole project without using migrate and deploy it on production env??Will not using migrate is disadvantageous??

Submitted April 29, 2020 at 09:17AM by meMindFlayer

Node.js Debugger | Tutorial 4

https://youtu.be/IQsi5eX9eCI

Submitted April 29, 2020 at 09:18AM by AllInOneForEveryone

Tuesday 28 April 2020

Do you have to npm install every time you open the command prompt?

No text found

Submitted April 29, 2020 at 07:31AM by saharshsamirr

Node v12.16.3 (LTS)

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

Submitted April 29, 2020 at 03:31AM by dwaxe

Advice for a total beginner?

Apologies if this isn't the right place for this sort of question, I'm feeling kind of lost here so please redirect me if necessary! I started working on a music visualization project during quarantine and stumbled across this awesome library on GitHub. I don't really have a ton of coding experience, but I've been messing around with the sample code and I've made a few neat looking visualizations that I'd like to be able to share with my friends. My problem is that without any past experience, I don't really understand how the code works well enough to know what I would need to do to be able to share my work.Right now, I run the code using the "Running Locally" instructions on the ReadMe. What would it take for me to be able to upload this code somewhere that I'd be able to see the visual output without the code running on my laptop? Are there any tutorials or online courses I can take that would give me the knowledge I need to accomplish this? How long would it take me to get to a point where I'm able to share this? I've spent the past few days trying to look into this by myself but I'm feeling overwhelmed by how much I don't know. Any advice or suggestions you have for me are very much appreciated! My ultimate goal is to be able to navigate to some sort of website that plays the visualizer. I'd also really like to be able to save the screen output to a video file format so I can send it to friends for feedback while I figure out how to share it publicly.

Submitted April 29, 2020 at 02:25AM by hannahofthenorth

In which Datatype should we store location data in sequelize for MySql

Hello Guys,I am working on a project stack(react native, express MySQL with sequelize).i need to add location data in my db. what datatype is should use? and how to do calculations based on distance like finding nearby 10 points ?Please help with example code too if possible..

Submitted April 29, 2020 at 02:39AM by meMindFlayer

New Express-Generator with ES6+ support and all new features

https://github.com/eklemen/generate-express

Submitted April 29, 2020 at 01:55AM by geek_nj_420

Pinning package.json dependency versions

I apologize for the basic-feeling question -- definitely not my area of expertise and 30 minutes of google searches failed me.TL;DR; = Is there a more automated CLI tool for quickly comparing pinned package.json versions to the versions available?The project I've been working on for a year (react-frontend / node-backend) went live two weeks ago. (YAY!) Now that we're done with most of the support requirements, etc., I want to take some extra steps make sure we're good to "walk away," without unnecessary support requests -- (and i think it would be nice to know this to help avoid future "we have a fire" scenarios that we see often enough in webapp development).I have manually pinned all of the `non-devDependencies` versions:// eg was: "react": "^16.13.0", // is now a "pinned" version, sans-caret: "react": "16.13.1", I didn't do this with devDependencies. A `^` semver value (to jest for example -- something in devDependencies) might pull in a minor update tho' that causes failing tests kills the CI/CD process.Is there a more automated CLI tool for quickly comparing pinned package.json versions to the versions available?

Submitted April 29, 2020 at 02:16AM by ArtDealer

Help with Node.js and Three.js

Hi everyone, i recently started learning Node along with Three.js and i've been having problems on the setup of my hopefully future website. I apologize in advance if my questions seem dumb but i've been learning for the past 2 months programming in general and i want to get out of the local website scope since i'm already comfortable with those and move on to a "bigger thing". I setup a nodejs server with the help of expressjs and i've been able to load the html part of my website, however the console of my browser doesnt seem to be loading my javascript file because it says `require is not defined`. The first line of my app.js is this `let THREE = require('three');` i created a package.json file inside a folder i created where i stored my html,css and js files. The installation of threejs through npm was successful( BTW, sorry in advance if what i'm doing is a huge oof). Outside of the folder i created a server.js where i installed express.js and used it to create a local server. Idk if the app.js isn't loading because i'm failing at the installation of the three.js library or if it's because i need a bundler which i saw a lot of people using for this purpouse i guess. Anyway, thanks if u got this far into the post. Here is how the whole project looks like https://imgur.com/gallery/lB6Q6W0

Submitted April 29, 2020 at 02:21AM by rogerpeke97

better-docs - documentation toolkit for node.js apps got v.2.0. Check it out - looks amazing

https://github.com/SoftwareBrothers/better-docs

Submitted April 29, 2020 at 12:18AM by hotcto

Can anyone help?

I want to change the content of an h1 to something the user typed in the form.How can I change the innerHTML of an html element by node js?

Submitted April 29, 2020 at 01:01AM by DagmawiBabi

Revert failed operations?

I have an endpoint that attempts to create/update a few documents in my DB (Mongo). Basically, its somewhat like this:Create an entityCreate another entityUpdate the first entity with the ID of the second entitySend 200Hypothetically speaking, something goes wrong and the second entity doesn't get created. So I send an error, and its all good, but now I am stuck with one stray entity. What would be the correct way to handle it? Potentially, I can just delete it but what if that hypothetical endpoint is creating / modifying more than just a handful of documents?Potentially, I could build some sort ofa system that "oversees" the whole process: if something happened say during Step 4, then revert/delete everything from Step 1 to Step 3, but it doesn't really sound like a good idea, does it?

Submitted April 29, 2020 at 01:05AM by pink_tshirt

TSSG - Web based Editor for Swagger Schema Generation

Hello Guys,I have been working on a tool that will help Backend Engineers write Swagger Schema in short and easy way and save them a lot of time as, we as Backend Engineers deal with Swagger a lot.I have released the Alpha Version to the public and still working on it to improve the overall user experience and adding more features as well. Please do check TSSG Editor and let me know if you think it’s useful for you and if you have any kind of feedback/suggestion/feature request, I will encourage you to comment here or even more better if you create an issue on the GITHUB REPO . Don’t forget to star the repo.Here the link to the editor https://jskod.github.io/tssg-editor/Thank you,Happy Coding

Submitted April 28, 2020 at 11:14PM by _jskod

Any Cloudinary Alternative That Has A Feature To Schedule Timeouts For File Deletions?

No text found

Submitted April 28, 2020 at 10:01PM by silverparzival

Help: Rest API with loopback 4

Hey guys, I’m working with loopback 4.There are couple of things I’m stuck on would be great if I have something to read about or a solutionThe database used is MSSQLI am trying to do a nested query with the models. If there is anybody with some experience achieving this. .find({ include:[ relation:’user’, scope: { where : { userId: 1 } }] }) This returns user: undefined if the where condition is not satisfiedsecondly, when I am doing a bulk insert I cannot use transactions with the datasourceThanks

Submitted April 28, 2020 at 09:20PM by wildbeardman

I made a simple TypeScript REST API boilerplate with integration tests and deployment example

https://github.com/nya1/rest-api-boilerplate

Submitted April 28, 2020 at 07:37PM by nya1v3r

node_modules appearing in Webpack source maps when using Yarn Plug n’ Play

So I started a new project and decided to use the new version of Yarn that has the plug n play functionality.Unfortunately though I am finding that source maps for the packages that I am using in the project are being generated when trying to use the browser dev tools.I’m guessing this is a quirk of how Plug n Play works. I’ve tried playing around with Webpack source map settings to get it to exclude node_modules but haven’t had any luck.Has anyone else experienced this and figured out how to fix it?

Submitted April 28, 2020 at 07:24PM by JaimieP

Why did is-promise happen and what can we learn from it - This isn't left-pad and I wrote why

https://snyk.io/blog/why-did-is-promise-happen-and-what-can-we-learn-from-it/

Submitted April 28, 2020 at 06:49PM by lirantal

Psi2d: a node web-based 2D shooting multiplayer

Psi2d is a web-based multi-player and mobile-friendly 2D shooter platformer.Node.js was for the perfect choice for such game: as you may know multiplayer (especially real time shooting games) must cope with lags, and the client must predict the world as long as it waits for updates from the server.With node I am able to use the same exact "game" class files (as well for ll dynamic objects inside the level game) and evolve the game world both in the client and in the server 💖.Instructions:  on mobiles: swipe on the lower side of canvas to move and jump; tap on the upper side of the canvas to shoot.on desktops: WAD/arrows/space to move; click to fireThe game is its beta version:Link: https://psi2d.itch.io/psi2dand here a small screenshot!

Submitted April 28, 2020 at 04:32PM by spocchio

I wrote a blog on using rust with nodejs napi

/r/rust/comments/g9nyo3/i_wrote_a_blog_on_using_rust_with_nodejs_napi/

Submitted April 28, 2020 at 03:16PM by argoyal

Post request 404 error?

Hello when i make post request to route /Auth/Register i get 404 error my code below. The get request works but post request dosent.const createError = require('http-errors'); const express = require('express'); const path = require('path'); const cookieParser = require('cookie-parser'); const logger = require('morgan'); const indexRouter = require('./routes/index'); const authRouter = require('./routes/auth') const app = express(); const Firebase = require("./Config/firebaseAuth"); let serviceAccount = require("./Config/devspacer-85c37-firebase-adminsdk-v8iq9-579733c529.json") let FirebaseContext = new Firebase(serviceAccount); FirebaseContext.connect() // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/Auth', authRouter) app.use(indexRouter); // catch 404 and forward to error handler app.use(function(req, res, next) { next(createError(404)); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); module.exports = app; AuthControllerconst GetRegister = (req, res) => { res.render("Auth/Register"); } const GetLogin = (req, res) => { res.render("Auth/Login"); } const PostRegister = (req, res) => { let {Username, Email, Password} = req.body; console.log(`${Username} , ${Email} , ${Password}`); return res.redirect("/") } module.exports = { GetRegister, GetLogin, PostRegister } Auth Routerconst express = require('express'); const AuthController = require("../Controllers/AuthController") const router = express.Router(); router.get('/Register', AuthController.GetRegister); router.get('/Login', AuthController.GetLogin); router.get('/Register', AuthController.PostRegister); module.exports = router; Html formdiv(class="auth-form-container") form(class="auth-form" ,action="/Auth/Register", method="post") label(for="Username") Username input(class="auth-form-item" ,required type="text", name="Username") label(for="Email") Email input(class="auth-form-item" ,required type="email", name="Email") label(for="Password") Password input(class="auth-form-item" ,required type="password", name="Password") input(class="auth-form-submit" ,type="submit", value="Register") a(class="link" ,href="/") Home

Submitted April 28, 2020 at 01:32PM by draganov11

Need help with my firebase project and storage access links to authenticated users

I have a firebase project where I have some authenticated users using firebase authentication. What we are doing is when a user leaves or gets de authenticated his/her file(say his image) in the storage also loses access i.e the permanent url becomes invalid even thought the backend isnt deleting the file, and when the user joins again they cant access their files. How can we do so that the url doesn't become invalid when the users gets de authenticated or to find a way to check whether the url's 'token' has expired or not

Submitted April 28, 2020 at 01:04PM by silenf

How to use swagger with sails.js?

Does anyone know how to set up/use swagger with sails.js version 1.2.3?

Submitted April 28, 2020 at 11:20AM by wh0d47

JSCasts ep18 - build an entire startup in Node.js part3 - file upload

https://www.youtube.com/watch?v=7WtKcFqJHho&feature=share

Submitted April 28, 2020 at 10:38AM by hotcto

I have a small problem

bear with me, this might sound stupid. and if there's a better approach for this let me know​I have a User and Post model, I'm trying to store an array of posts on a specific User whenever he clicks 'Add to favorite' button. I'm adding them successfully. but I'm not able to remove it from that array. (I'm sending a boolean value to check)I'm trying to console.log the array after the filter method but nothing is being displayed.. here's my code:https://preview.redd.it/58grt8g8oiv41.png?width=1366&format=png&auto=webp&s=758bb50896558b3d2eaacb96855b2fb428f7f5a1and here I tried to console.log it outside the else block, but it was executed before the else blockhttps://preview.redd.it/65k559pyniv41.png?width=1366&format=png&auto=webp&s=dce5394e87c15801e08b37afaad21f0149577b1e

Submitted April 28, 2020 at 09:12AM by Sakalalaa

Is there a solution for storing a few global variables that can be updated during runtime and will keep their value even after server restart?

So I know that the title making it sounds like "yeah use a DB", but I use MySQL and I don't think that creating an entire table just to have a single row in it is the best solution... also as I explain in the next line the variable will affect the functionality of the server and it's not a good idea to pull the variable from the DB every time before using it (just so that the server will always use the newest values)So the variables that I need to store basically can be defined by me or any one of the other admins (non-dev guys) through our admin console (built with React, not that it really matters), and the variables will affect a lot of stuff during runtime and if a variable is being updated then it should keep its new value even if the server restarts...Also I want the solution to support multiple processes (when load balancing) so all the processes will use the newly updated variables...

Submitted April 28, 2020 at 08:02AM by s_trader

Monday 27 April 2020

How to test faking an user is logged in?

Hello all,I am trying to test some of my routes that require an user logged in using Jest + supertest. I use jspassport and I create a session per user logged in. The session ID is stored in a cookie.The problem I am facing is that when I run the test, I do a request to login and it returns status code 200, so it seems ok. However, if I do a subsequent request to a route that requires login it does not work. I guess it is because there is no session id attached in the cookie as there are no cookies when running the test (correct me if I am wrong please).Therefore, how would you tackle this problem?Thank you in advance and regards

Submitted April 28, 2020 at 07:05AM by dejavits

prefix issue

hi im having a prefix issue when i run the code through discord

Submitted April 28, 2020 at 02:47AM by hellob2

Install modules

​I did use python with visual studio because I wanna learn coding the first day of quarantine but i still dont understand so i decided to use nodejs instead but should i install necessary tools??

Submitted April 28, 2020 at 03:35AM by Lil_angel1912

Will MongoDB prevent Read Operation during Atomic Transaction

As per title, either for single document or multi-document atomic transaction, will Mongo prevent read operation while it’s performing atomic write transaction?I’m worried that the application will read the old data while Mongo is still updating the data in the atomic write transaction. Then, this old data is used to update the database, instead of using the new data.Or will MongoDB atomic transaction prevent subsequent query to be performed before the current atomic transaction is completed, so that the query will read the updated data? What if the atomic transaction takes a long time, will this be prevented with Mongo inner mechanism?

Submitted April 28, 2020 at 01:40AM by VickNicks

Security Research Questions

I'm studying over the summer with a professor for an undergraduate research course. I want to focus on Node.js web security protocols and techniques. My goal is to learn the most practical approaches to web security. I understand that most of web security involves proper data validation and sanitation, as well as proper error logging. Most of the topics I have so far are taken from the OWASP top ten. If you were to recommend a node.js security topic for me to look into, what would it be?Thanks a ton to anyone who replies, I am super excited to learn about the security side of Node web development.* As of now I have only worked with basic API authentication/authorization (express sessions, JWT), password encryption, and input validation (mongoose + Joi)

Submitted April 28, 2020 at 12:16AM by Sandmanndh

What are all of the little tricks and techniques you can use to make your Node.js application more scalable?

These are the ones I know of:caching (redis) pagination child process forking (node.js) worker threads (node.js) database sorting (sorting on the db side, node.js) Could you list them all for me?

Submitted April 27, 2020 at 10:48PM by jasonscript

SyntaxError: Unexpected end of JSON input at JSON.parse ()

Hi, I'm making a web app that uses the api from a game and I'm currently trying to diplay general information about the searched user. When I go to the url that I get the user data from, it's clearly a JSON, so why do I get this error when I try to call JSON.parse(data)? 'data' contains the user information. I tried searching for solutions and couldn't find anything that could help me...

Submitted April 27, 2020 at 10:11PM by McTex_reddit

Ubuntu 20.04 is out, but Nodesource *.deb still depends on python2

Ubuntu 20.04 LTS (Focal Fossa) is out and of the features proudly mentioned in the release notes, it that they got rid of python 2 and now only require python 3 by default. Finally!When I wanted to install Node.js using the binary package provided by NodeSource, I found that even the latest 14.x version still depends on python2-minimal. I mean, come on! It's 2020, and we shouldn't be required to use this ancient, end-of-life version of python. Why is python required anyways? I did not find any consistent information, seems that node, npm and node-gyp all blame each other.Does anyone know if there is a way to install Node.js without python2? (No, I can't use the Snap version, because a) I don't like it and b) I get a GLIBC error when I want to use the dependeny 'serialport')

Submitted April 27, 2020 at 10:09PM by bildanderwand

Updating single fields in an entry using express router

Hello all. Creating my first app with MERN, I'm trying to establish endpoints for CRUD ops. The tutorial I was following used express router for get and post requests to a mongodb, but the tutorial was sending every field an entry needs for a collection.I am just wanting to update a single field in an entry instead of having to send all the extra information again.right now I have a route that I only want to toggle an active or deactive flag for the userRoutes.route('/user/:id/deactivate').put(function(req, res) { USER.findById(req.params.id, function(err, user) { if(!user) { res.status(404).send("data is not found"); } else { user.user_active = req.body.user_active; user.save().then(user => { res.json('User updated successfully!'); }) .catch(err => { res.status(400).send("Update not possible"); }); } }); }); the model for the user is{ "user_name": "T. Elliot Sanders", "user_address": "100 west rd", "user_phone": "123456789", "user_cart": { "items": [], "total": 0, "formattedTotal": "0" }, "user_active": true } but when I run the route using postman to only update the user_active flag to false the entry in the collection has everything deleted except the user_active field. so after the route the entry is{ "user_active": false } So how do I update the single field, but not delete the others, but also not have to resend information that has not changed?

Submitted April 27, 2020 at 09:38PM by notalentnodirection

How to deploy a socket.io based project?

I've made a 1 vs 1 card game that has to be played on the terminal. I used socket.io and node.js for this. I have no previous experience on deployment, so will this application be deployed normally or do i have to do something else?I'm confused whether normal deployment would enable users to play the game in their terminals against each other.

Submitted April 27, 2020 at 08:51PM by DeusExMachina24

Twitter API in JavaScript - Twitter Monitoring Tutorial

https://youtu.be/jpV1B2N4IxY

Submitted April 27, 2020 at 05:56PM by TomekB

How can I set both ObjectId and UserId in MongoDB(Image attached)

I saw an example online where there is an ObjectId and also the productId as seen in the image below.https://preview.redd.it/xjlocwqc5ev41.png?width=1260&format=png&auto=webp&s=ebfc4ea40eb1628d7a548fde5a6d876cf53c8ce8I have a schema that looks like thisimport * as mongoose from 'mongoose'; import * as bcrypt from 'bcrypt';export const UserSchema = new mongoose.Schema({ userId: { type: mongoose.SchemaTypes.ObjectId,     }, firstname: { type: String, required: true     }, lastname: { type: String, required: true     }, });With this schema, I can only see the objectId the DB, and every time I do thislet user = await this.userModel.findById({ '_id': new ObjectId(id) }) I get this errorCannot find name 'ObjectId'. Did you mean 'Object'?ts(2552) lib.es5.d.ts(267, 13): 'Object' is declared here. So I think it will be ok to get BOTH userId and document ObjectId just like what is in the image above\Thanks

Submitted April 27, 2020 at 06:10PM by techstackng

Scan your project for unrequired files

/r/webdev/comments/g94xh6/scan_your_project_for_unrequired_files/

Submitted April 27, 2020 at 06:16PM by smeijer87

Making multiple GET requests to an API that limits the number of calls per minute to 100

What are the options to make multiple GET requests to an API that limits the number of calls per minute to 100? I need to get a lot of records from an API and I've found that it's easy to exceed this amount without receiving all of the data I need.For example, is it possible to make a request, get the response, and then wait for a second before making another request? If so, what is the best way to manage this?

Submitted April 27, 2020 at 05:32PM by xiii_xiii_xiii

How are these authentication methods implemented in node?

​Web backend developer roadmap 2020Form the above pic.(Web developer roadmap 2020) , How are the solutions implemented for all these authentication methods in node? References to tutorials, websites, blogs all are welcome.

Submitted April 27, 2020 at 03:54PM by KeyboardScript

is-promise post mortem

https://medium.com/@forbeslindesay/is-promise-post-mortem-cab807f18dcc

Submitted April 27, 2020 at 04:04PM by ForbesLindesay

tstl-singleton, asynchronous singleton generator

https://github.com/samchon/singleton

Submitted April 27, 2020 at 03:27PM by SamchonFramework

Deno - introduction & comparison with Node.js in 5 minutes.

Have you guys checked out Deno yet. It is a project by Ryan Dahl who created Node.js.If you have heard about it, or want to know more. Please watch the video.Hope you like it. Also comment what you think about it.https://www.youtube.com/watch?v=Z_tbaqdW1LE

Submitted April 27, 2020 at 03:16PM by abhikul22

Middy 1.0.0 is here - the Node.js middleware framework for AWS Lambda

https://loige.co/middy-1-is-here/

Submitted April 27, 2020 at 02:47PM by pmz

Stay in control with your private NPM registry

https://medium.com//stay-in-control-with-your-private-npm-registry-f7d1d4791698?source=friends_link&sk=a4dce912ed2f75b58fcb816b6d5e9752

Submitted April 27, 2020 at 02:06PM by Fewthp

Node.js singleton patterns

I'm having a debate with a colleague about good patterns for singletons in NodeJS.Currently I have a module that looks like this:async function doSomethingExpensive() { // do expensive async thing (DB calls, etc) return result; } export const SOMETHING_EXPENSIVE = doSomethingExpensive(); This results in the desired behaviour (which is doing the expensive thing once), so long as you wait on the constant elsewhere in the code (await SOMETHING_EXPENSIVE). Which looks a bit weird.Is there a nicer way to do this that lets us await on a function and is understandable?One option is simply:async function doSomethingExpensive() { // do expensive async thing (DB calls, etc) return result; } const SOMETHING_EXPENSIVE = doSomethingExpensive(); export const getSomethingExpensive = async () => SOMETHING_EXPENSIVE; This is the same, but allows us to await getSomethingExpensive() which doesn't look so weird.I also pondered doing it with Promise, because in some ways that's clearer here:const SOMETHING_EXPENSIVE = new Promise((resolve, reject) => { // do expensive async thing (DB calls, etc) resolve(result); }); export const getSomethingExpensive = async () => SOMETHING_EXPENSIVE; My colleague contends the following would work, but I think this isn't guaranteed to only do the expensive thing once, because both guard conditions may be run in the event loop before the expensive operation. Is my understanding of the event loop correct?let SOMETHING_EXPENSIVE = null; export async function getSomethingExpensive() { if (SOMETHING_EXPENSIVE) return SOMETHING_EXPENSIVE; // do expensive async thing (DB calls, etc) SOMETHING_EXPENSIVE = result; return SOMETHING_EXPENSIVE; } I think the above won't work correctly (although might do in practice 99% of the time).Thoughts?

Submitted April 27, 2020 at 01:31PM by ianjm

TypeScript Express tutorial #15. Using PUT vs PATCH in MongoDB with Mongoose

https://wanago.io/2020/04/27/typescript-express-put-vs-patch-mongodb-mongoose/

Submitted April 27, 2020 at 11:25AM by _gnx

spawn child_process: keep alive for input

I have this very simple spawn command, where (if not logged in) you'd need to enter email and password (one after each other). However, the command exits immediately after it completes and thus i can never input login details.window.terminal = spawn("nordvpn", ["login"], {env: process.env,shell: shell,cwd: process.env.HOME});later..window.terminal.stdin.write('myUsername');Which gives me an error:Error in v-on handler: "Error [ERR_STREAM_DESTROYED]: Cannot call write after a stream was destroyed"Can anyone help me out here? Thanks alot!

Submitted April 27, 2020 at 10:32AM by martijn-fme

What are your thoughts on Linkedin Learning's node pathway?

I want to start learning nodejs and I have access to linkedin learning. and I found this pathway along with other advanced pathways for node.. So, what do you think about this Node.js Developer pathway .Is it good enough ? or should I look for other resources? .. and what resources would you recommend

Submitted April 27, 2020 at 09:42AM by i-mw

Sunday 26 April 2020

Dunno how this would be useful, but i made a shift register

let shiftRegister = class { constructor(bits) { this.register = [] for (let i = 0; i < bits; i++) { this.register[i] = 0 } } addData(d) { if (typeof d === 'object') { for (let i = 0; i < 8; i++) { this.register[i] = d[i] } } if (isNaN(parseInt(d)) || d === 0) { d = 0 } else { d = 1 } this.register.unshift(d) this.register.pop() } get data() { return this.register } }

Submitted April 27, 2020 at 07:40AM by GingkathFox

[Win10] Terminal Not Working

Hey All,Very new to node, coming from python! Just downloaded node.js and can't seem to get the console to display a simple "hello world". I've got my app.js file which just has "console.log('hello world');" and I'm using "node app.js" to run the app in my cmd terminal, but I don't see a response in the terminal.I know node is installed because "node --version" yields the correct version. And I checked to make sure that it is in my path as well.Not sure what I;m missing here - thanks!https://preview.redd.it/doxfehj6pav41.png?width=545&format=png&auto=webp&s=744c4339b1746f5d7780a793e75128f3f0f9e5fa

Submitted April 27, 2020 at 06:21AM by user2m

How can I find all item names in a Postman collection that’s exported as JSON?

I have this MASSIVE Postman collection that has dozens of folders and sub-folders. I want to know if it is possible to use NodeJS to find each of the folder names in that JSON file then create those folders on my local MacOS file system. It would be extremely manual for me to do this without an automated way.

Submitted April 27, 2020 at 04:56AM by Rlyhyper

This problem comes and goes at random and affects any node project I run.

Here is a git repo with the project I am working on​So I'm having an issue and I don't know what I'm dealing with. I hope someone can point me in the right direction.I have been going through MERN stack tutorials and I didn't seem to have this issue when I started but now seemingly at random, I will throw loads of Content Security Policy errors.​Content Security Policy: The page’s settings blocked the loading of a resource at inline (“default-src”). injectGlobalHook.js:1:1730 Content Security Policy: The page’s settings blocked the loading of a resource at data:application/font-woff2;charset=utf-… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:application/font-woff;charset=utf-8… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAJAgAB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAI7sAB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:application/font-woff2;charset=utf-… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:application/font-woff;charset=utf-8… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAJAgAB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAI7sAB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAIw4AB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAEzMAB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAI7kAB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAI3gAB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAIt0AB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAIw4AB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAEzMAB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAI7kAB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAI3gAB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAIt0AB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAG1gAB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAGvEAB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAGz8AB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAGVUAB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAG1gAB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAGvEAB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAGz8AB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAGVUAB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAKD5AB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAJd6AB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAKD5AB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at data:font/woff;base64,d09GRgABAAAAAJd6AB… (“default-src”). Content Security Policy: The page’s settings blocked the loading of a resource at http://localhost:4000/favicon.ico (“default-src”). Currently, I'm trying to test API endpoints for a project and when I open localhost:PORT in a browser I get these errors and the body of the page says Cannot GET /. These errors will show up for any node server I start, eventually the errors go away on their, so I stop working on it, but eventually the errors show up again.​Does anyone know what I could be doing here? I feel like I may have borked something going through the tutorials, the only thing that was installed globally was nodemon if that helps.

Submitted April 26, 2020 at 11:11PM by notalentnodirection

Can I Send JavaScript Object Variables to SQLite as a Blob?

This may be a vary basic question and I'm just not wording my Google search correctly, but I'm writing a simple CRUD app and I have some my data in objects, can I just send the object to SQLite as a blob type and then retrieve it later?

Submitted April 26, 2020 at 10:14PM by coffeepostal

Auto Clicker for games

const r = require("robotjs"); const ioHook = require('iohook'); const state = { working: false, } ioHook.on("keyup",function(keyPress){ // numpad 1 if (keyPress.keycode === 79) { state.working = true } // numpad 2 if (keyPress.keycode === 80) { state.working = false } }); ioHook.start(); setInterval(() => { if (state.working) r.mouseClick('right')}, 500) simple and works alrightly.run after installing robotojs and iohook :D

Submitted April 26, 2020 at 09:18PM by fistyit

Got sick of configuring TypeScript packages so often so wrote a tool that takes all the pain away, introducing ts-engine

https://ts-engine.dev

Submitted April 26, 2020 at 09:04PM by highres90

I made a shareable timer as beginner, waiting for your feedbacks

https://ahmetbcakici.github.io/justimer-client/

Submitted April 26, 2020 at 08:22PM by ahmetbcakici

How Would You Setup Your Node.js Environment To Prevent DOS/DDOS Attacks?

No text found

Submitted April 26, 2020 at 07:34PM by silverparzival

Why request.getHeader doesn't work on request object on NodeJS server handler?

Hello. I've been playing with NodeJS and reading, and probably I'm missing something. As I learned, it is possible to use ClientRequest object to invoke REST APIs from NodeJS itself in a vanilla way (more complicated that just use Axios, but still).As I could check, I can set and get headers from it using setHeader() and getHeader() in the following way:const req = http.request({});req.setHeader('Content-Type', 'application/json');req.getHeader('Content-Type');but, when using ClientRequest for handling incoming requests in a NodeJS server, using getHeader() does not work, returning the error function req.getHeader() function does not exist. As I learned later, you can do request.headers to access an array of headers with lowercase names to not to worry about casing.const server = http.createServer((req, res) => {//const contentType = req.getHeader('content-type'); --Doesn't workconst contentType = req.headers['content-type]; // It works!...}However I don't get why getHeader() only works in a context but not in the other.

Submitted April 26, 2020 at 06:52PM by anicetito

Help: Why is my image file not complete in this function? (fetching URL to writestream)

Heya. JS Noob here and I hope these type of questions are allowed. I appreciate and help/guidance on this. I've been pulling my hair out for days now on this.I am trying to upload an image from a URL to my Google Cloud Storage (Firebase). The following function shall return the file and a consecutive function will retrieve the actual Signed/Download Url to the new file. After all this I am updating a document in my Firestore Database with the new URL. That part works; the functions wait on uploading the (unfortunately incomplete) image and my document gets updated with the newly created file url. But the actual file/image is incomplete. :-(Here is what the Image actually looks like: https://imgur.com/a/KlYaPSRHere is my current iteration of my code, which I have changed, rewritten and went through trial and error.async function saveToStorage(fileUrl) { var storage = admin.storage(); var urlLib = require("url"); var pathLib = require("path"); //Get File Name from provided URL var parsed = urlLib.parse(fileUrl); var fileName = pathLib.basename(parsed.pathname); //Create Storage Reference with new File Name var bucket = storage.bucket('gs://myprojectname.appspot.com'); //Path Folder var folderPath = 'data/photos/'; //Path Folder + File var internalFilePath = folderPath + fileName ; //Bucket File Ref var file = bucket.file(internalFilePath); const request = require('request'); const writeStream = file.createWriteStream({ metadata: { contentType: 'image/jpg' } }); return new Promise((resolve, reject) => { request.get(fileUrl) .pipe(writeStream) .on("error", (err) => { console.error(`Error occurred`); reject(); }) .on('finish', () => { console.info(`Photo saved`); resolve(file); }); }); } I have tried using node-fetch and request and rewrote my function in several ways, but always turn out with this result. I'm sure it has something to do with how I use my Promise, because if I omit the Promise the file actually completes but then the main code keeps executing instead of waiting for this Promise.Thanks for any help!

Submitted April 26, 2020 at 06:05PM by Hagbard321

What's Async Local Storage in Node.js v14?

https://www.freecodecamp.org/news/async-local-storage-nodejs/

Submitted April 26, 2020 at 06:16PM by M_Nano

What would be the best javascript learning path for backend?

/r/learnjavascript/comments/g87cpb/what_would_be_the_best_javascript_learning_path/

Submitted April 26, 2020 at 05:00PM by chul-ian13

Beginner question: How to upload a nodejs app onto my server and let it run via cronjob?

Hey theresorry if this question sounds silly, I am new to "automatisation via scripts" but I have a question.I have a hosting at namecheap.comI have successfully programed a scraper with puppeteer.When I run the script - it works fine and is scraping my instagram follower via puppeteer scraping.Now I want to upload the script and let it run once an hour but here is my question:What do I need to do this?How do I install puppeteer on my webhosting?I've tried to upload all files there but it says I need a package.json - which I have uploaded but .... I right I'm doing something wrong.I have simply made a waterfall algorithm - nothing fancy - do everything step by step ...Maybe someone can help me :) Really appreciated!

Submitted April 26, 2020 at 04:25PM by HammerH89

Destructuring always creates a new instance of a value.

I recently faced an issue in my tests where stubs did not work at all.I am using the got library to make HTTP requests and no matter how I stubbed the HTTP methods, the API calls would always go through no matter what.Turns out the answer to this issue was quite a simple principle that I could not place directly. Destructuring will always create a new instance of a value and will not point to the same value anymore.The functions were destructuring the HTTP function and the test was importing a new instance of the HTTP function that would not get stubbed.I wrote this up on my blog detailing on what was happening and how we tried fixing it temporarilyhttps://blog.eyadkobatte.com/making-sense-of-destructured-imports-for-testing-and-stubs/

Submitted April 26, 2020 at 03:28PM by eyadkobatte

2 Player game using Mobile phones as controllers

HiI've used Node, socket.io and P5 to create a game that combines a bit of pong and breakout.You can use a TV or PC screen as a game display, and your mobile phone as a controller.Feel free to take a look here http://18.224.39.75:3000/Enjoyhttps://preview.redd.it/edl5xay056v41.png?width=616&format=png&auto=webp&s=1aee6e00eae69bfee7810f9e3c7a2e83cfb9903c

Submitted April 26, 2020 at 02:59PM by nuno20090

How to work with jwt tokens

Hi there! Ive spent the whole day on learning jwt (json web token) and I can managed to authenticate using postman api using the ‘Authorization’ header. This is convenient in the postman.What I want to do is to let the browser know that im logged in. That if the user tries to go to login page it will be redirected to his dashboardMy question is how do I setup token in the real web application?

Submitted April 26, 2020 at 03:10PM by SlightExplanation

A question about hosting app

I am working on a learning project. I have build a authentication system in nodejs using local and Google strategy. Front end is a react app. There are two options for hosting 1. Deploy front end on static hosting providers like netlify or github pages and backend node app to heroku. 2. Deploy both backend and front end on heroku with front end code in the public folder and use express.static('public')I am confused in both these approaches and could not find answer on internet. It will be a lot of help if you can explain pros and cons of both the method and which on is suitable in what conditions. Links to the articles is also appreciated. Thank you in advance.

Submitted April 26, 2020 at 02:02PM by eric_cart

What are your reviews about egg.js (Nodejs framework)?

I have searched for similar question and found quite old question with little activity. Now that some time has passed, I am sure many of you would have used it in production or in personal projects.So what are your reviews about egg.js? Is it worth learning? What are your thoughts about its architecture, modules, packages? performance?I'm using Nestjs at job but I am not a fan of Nestjs mainly because of its complexity. So I am looking into egg.js as I am already using frameworks and libraries from their developer (xtech) and I really like their products.

Submitted April 26, 2020 at 10:53AM by one_lame_programmer

Cain-Stack a Full-Stack JS template to quickly build native cross platform applications with web technologies. Based on CouchDB, Angular, Ionic & NestJS. Offline Storage, native APIs and authentication included.

https://git.heichling.xyz/max/cain-stack

Submitted April 26, 2020 at 11:02AM by iotahunter9000

Are social logins becoming more popular?

I am thinking of implementing social login for a site. I have read that consumers prefer using google sign in as opposed to signing up on yet another website. The problem is that I find that complicated to implement.So my question is, is social login really increasing in popularity? If so, is there any data to back that up?Thanks

Submitted April 26, 2020 at 07:36AM by ilovefunctions

Saturday 25 April 2020

An easy CRUD operation based on Factory pattern with Mongoose. Create, Read, Update, Delete with pagination, sorting, and population.

https://www.npmjs.com/package/quick-crud

Submitted April 26, 2020 at 07:17AM by rayhan666

What excites you the most about the future of React Native?

/r/expojs/comments/g86k3i/what_excites_you_the_most_about_the_future_of/

Submitted April 26, 2020 at 03:39AM by SynthesizeMeSun

Building a Node Server with NestJS - Coding Corner with Tyler - Candee Generations

https://youtu.be/7MDgVFIFKew

Submitted April 26, 2020 at 12:39AM by av_enger

Adding GraphQL to our NestJS Server - Coding Corner with Tyler - Candee Generations

https://youtu.be/eLpTvMLeDKs

Submitted April 26, 2020 at 12:40AM by av_enger

Looking to build a team for a project, so I built a team building site with node.js for the backend. Anyone interested in joining?

https://www.unilous.com/

Submitted April 26, 2020 at 12:42AM by 1sosa1

Pulling single field from mongoDB query

Hey guys so I'm very much a noob when it comes to this stuff.I'm working on a course project creating a very simple google cloud function that will operate with a web front end. All I'm doing is running an aggregation to get the average of a particular field grouping and I want to then send that back to the database.I'm getting stuck on attempting to pull the single field from the average aggregation, I've found I need to use JSON.stringify() and then JSON.parse() but I'm getting an error saying that my query has circular logic. I do not see where it is really getting that from but nonetheless thats why I'm here asking for help.Here is the code in question (please be nice I'm new to this haha) (i've bolded what is the relevant section)const co = require('co');const mongodb = require('mongodb');const uri = 'mongodb+srv://USERNAME:[PASSWORD@cluster-gpld2.gcp.mongodb.net](mailto:cafuba101@cluster-gpld2.gcp.mongodb.net)/test?retryWrites=true&w=majority';exports.calculateRating = (req, res) => {  co(function*() {const client = yield mongodb.MongoClient.connect(uri);let userID = req.body.userID || req.query.userID;let submittedRating = req.body.submittedRating || req.query.submittedRating;let steamID = req.body.steamID || req.query.steamID;//check if user has rated the game beforeconst count = yield client.db('Games').collection('ratings').find({"steam_appid": parseInt(steamID), "user": userID}).count();//if the user has rated the game update their rating instead of making a new ratingif(count >= 1){      client.db('Games').collection('ratings').update({"steam_appid": parseInt(steamID), "user": userID}, {$set: {"rating": parseInt(submittedRating)}});//calculate average ratingconst averageJSON = client.db('Games').collection('ratings').aggregate([{$match: {'steam_appid': parseInt(steamID)}}, {$group: {_id: '$steam_appid', ratingAverage: {"$avg": "$rating"}}}]);const averageString = JSON.stringify(averageJSON);const result = JSON.parse(averageString);//insert average into games collection      client.db('Games').collection('Game_Info').update({"steam_appid": parseInt(steamID)}, {$set: {"rating": parseInt(result.ratingAverage)}});res.send('Your rating has been updated to: ' + submittedRating + result);}//otherwise make new rating else{//insertionyield client.db('Games').collection('ratings').insertOne({"steam_appid": parseInt(steamID), "user": userID, "rating": parseInt(submittedRating)});//TODO: calculate average rating      res.send('Your rating of ' + submittedRating + ' has been submitted. ' + JSON.stringify(average.ratingAverage));    }  }).catch(error => {    res.send('Error: ' + error.toString());  });};

Submitted April 26, 2020 at 12:04AM by TyranoMike

NodeJS Backend | Critical NGINX Unit situation

Hi everyone,I'm currently working on a big project that involves the use of a large amount of financial data, classification, and analysis through aggregations and regular expressions performed directly on JSON arrays.I figured all this stuff out quite easily, but here comes the BIG problem,the backend of the webserver which should be responsible for all this data visualization.I know you might ask why... WELL because, to be honest, I'm new to all this backend stuff, pm2, expressJS, and mostly NGINX Unit and all the knowledge on reverse proxy I don't possess.After a week of disparate web searching for guides, documentation on NGINX Unit(besides the official documentation), and reverse proxy I decided to play my last card.Ask for help on Reddit. So I need a lot of help as you might figure out already and I will be so glad if someone can explain all these backend details to me or provide any useful links or documentation.Thank you all very much.

Submitted April 25, 2020 at 09:22PM by condrove10

Easy way to know something is a dev dependency?

It seems obvious even from a Google search:For example testing packages, webpack or Babel.So Axios, I am using that, when I run the build, isn't that turned into like plain XHR or something, so it could be considered a dev dependency?In my particular case I'm using create-react-app and using npm run build for my "production"I imagine it would be different if I'm deploying say an Express API where I need something like multr but even that... doesn't that get turned into plain JS. I'm not "shipping" static files but running libraries so I could see these being needed/not dev dependencies.I guess when/why does this matter... just lines in package.jsonI guess sending unneeded files/extra bytes

Submitted April 25, 2020 at 06:22PM by post_hazanko

New Nuxt Project

I'm starting a web/mobile app. I'm a full stack web developer. I've started using nodejs for a lot of my new projects. I have a Web/Mobile App that I am starting. It's straight forward with nothing crazy special as far as functionality but the target customer for the app is basically anyone with a child 4 to 16. The app has tons of potential. I just need help building it. I believe Nuxt is the most elegant framework for it. If anyone is interested come hang out in the discord and chat with me. https://discord.gg/4nXbuY Would love to pick some other developers minds.

Submitted April 25, 2020 at 03:52PM by jamie337nichols

In march, the german government started a hackathon to develop solutions for the corona crisis. We are one of the top 20 teams and are in need of volunteers for NestJS development!

Hi, I'm on the volunteer team for one of the top 20 projects in the German government's WirVsVirus Hackathon. We (nexd) are developing a platform to coordinate grocery shopping helpers for all those who cannot leave the house at the moment. The twist here is that even people without a smartphone and technical knowledge can submit their shopping list via a simple phone call. This way, we reach the people most affected by the crisis: seniors.We are about to launch the beta test but are in dire need of NestJS developers for our backend. If you are interested in helping (our slack is in English) please contact [mail@nexd.app](mailto:mail@nexd.app)More information about the project (German only, sadly): https://www.youtube.com/watch?v=0PmuLrq4HnoGitHub: https://github.com/NexdApp/nexd-backendThank you and stay healthy!(sorry for repost but the title was wrong and it's not possible to edit post titles)

Submitted April 25, 2020 at 04:08PM by andre-stefanov

How do I fix this error guys? It says an unexpected token at line 39

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

Submitted April 25, 2020 at 01:17PM by Nikhil_Aryal26

Recommentaion for free Node APM?

Hi, I need to monitor my server in a nice and fashion way with some cool charts.I need some characteristics like logging, error tracking and real user monitoring.What free APM do you use and recommend?Thank you!

Submitted April 25, 2020 at 01:28PM by patilanz

Values of mongoose created object returning undefined

How can I access my NodeJS server that's running on my localhost from other PCs on my local network?

So I have on PC number 1 my NodeJS server running and I have PC number 2 in which I want to be able to browse to my NodeJS server that's running on PC number 1Both of the PCs are connected to the same wifiI've tried:add "0.0.0.0" / "127.0.0.1" / my public IP / my IPv4 to my "listen" functionaccess the NodeJS server from my public ip / ipv4 (of course on the same port it's running on my PC)use ngrok (which is the only solution that actually works, but is very slow due to it using a tunnel and me using the free version)I'd love to get some help with this issue :)

Submitted April 25, 2020 at 08:40AM by s_trader

Friday 24 April 2020

Image uploads corrupted (Next.js, Azure Block Storage)

Hi all. I'm having trouble uploading images in my Next.js project.From my React component I'm submitting a form via these functions: const fileUpload = async (file: File) => { const url = '/api/image' const formData = new FormData() formData.append('file', file) const config = { headers: { 'content-type': 'multipart/form-data', }, } const response = await axios.post(url, formData, config) const { data } = response return data } const handleSubmit = async (event: React.SyntheticEvent) => { const url = '/api/post' if (files) { // ignore fileUpload(files[0]).then((response) => console.log('submit response', response) ) } event.preventDefault() } And the API route in Next looks like this:import formidable from 'formidable' const fs = require('fs') const { BlobServiceClient } = require('@azure/storage-blob') if (process.env.NODE_ENV !== 'production') { require('dotenv').config() } const AZURE_STORAGE_CONNECTION_STRING = process.env.AZURE_STORAGE_CONNECTION_STRING export const config = { api: { bodyParser: false, }, } const getBlobName = (originalName) => { const identifier = Math.random().toString().replace(/0\./, '') return `${identifier}-${originalName}` } export default async (req, res) => { const form = new formidable.IncomingForm() form.keepExtensions = true form.uploadDir = './public/static/uploads' form.parse(req, async (err, fields, files) => { if (err) { return } return res.json({ fields, files }) }) form.on('file', async (name, file) => { const blobServiceClient = await BlobServiceClient.fromConnectionString( AZURE_STORAGE_CONNECTION_STRING ) const containerClient = await blobServiceClient.getContainerClient( 'images' ) const buff = fs.readFileSync(file.path) const data = buff.toString('base64') const blobName = getBlobName(file.name) const blockBlobClient = containerClient.getBlockBlobClient(blobName) blockBlobClient.upload(data, data.length) }) } The image which gets stored locally is corrupt and looks like a TV tuned to a dead channel. I'm clearly not encoding it properly — but unsure whether it's my ContentType or the string encoding?​Thanks!

Submitted April 25, 2020 at 06:41AM by acpatrice

Funny names to gives your libs

Hello happy people.You know how most modules have a funny name related to what they do.Well, I am building a centralized permission/authorization micro-service and I need a name for that thing. The service will be responsible to deliver entity/resource/action based permissions.Do you have any recommendation of funny/clever names OR a domain/universe that I could pick a name from?Thanks for your time.

Submitted April 25, 2020 at 02:17AM by joeyrogues

Why console.log and errors aren't shown in chrome dev tools when using EJS?

I have a simple express setup with ejs layout:app.use(express.static('public')) app.use(expressLayouts); app.set('view engine', 'ejs'); My register.ejs with a script tag at bottom: In my index.js in public folder:console.log('Hello world!');console.log doesn't display or errors only show at the top right corner of the dev tools.Can anyone explain?

Submitted April 25, 2020 at 02:35AM by huyzzz

I made a video discussing the importance of microservice automation with Docker for my VENM (Vue, Express, Node, Mongo) stack web app. I'm still beginner, but learning this new process has saved me a lot of time and headache. I definitely recommend using/learning Docker for NodeJS apps!

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

Submitted April 25, 2020 at 02:58AM by TeluguGameboy

Library for Prioritizing Promises?

I've run into a use case that I can't seem to find a library for and I figured I'd ask here before I write one myself.Basically I need to request resource A, and if it fails, fall back and request resource B, and so on. For performance reasons, I want to fire off all the requests at once. However, I can't just use Promise.any or Promise.race because it's not guaranteed that resource A will return first. I also don't want to use Promise.all because I want to return as fast as possible, ignoring or cancelling any requests that haven't finished. I need to return if A resolves, or A rejects and B resolves, etc.Anyone know of a library that solves this elegantly?

Submitted April 25, 2020 at 01:41AM by Y33zma

Next.js | Environment Variables and Runtime Configuration

https://www.youtube.com/watch?v=Mh9BJNfAVsM&feature=share

Submitted April 25, 2020 at 12:55AM by bmvantunes

Vadoo : Project aiming to reduce video streaming costs up-to 30% built on webrtc and websockets

Hello all. During the course of the pandemic we have seen Netflix/Prime reduce their resolution to bear the costs and to deal with increased demand. To address this I have built a solution based on distributing load across peers.The solution can reduce video streaming costs by up-to 30% and improve the scalability by 6xWould love to get some feedback from you allLink :- https://gitlab.com/Vadootv/android-sdk/

Submitted April 24, 2020 at 10:03PM by ANil1729

In march, the german government started a hackathon to develop solutions for the corona crisis. We are one of the top 20 teams and are in need of volunteers for swift development!

Hi, I'm on the volunteer team for one of the top 20 projects in the German government's Wir Vs Virus Hackathon. We (nexd) are developing a platform to coordinate grocery shopping helpers for all those who cannot leave the house at the moment. The twist here is that even people without a smartphone and technical knowledge can submit their shopping list via a simple phone call. This way, we reach the people most affected by the crisis: seniors.We are about to launch the beta test but are in dire need of NestJS developers for our backend. If you are interested in helping (our slack is in English) please contact [mail@nexd.app](mailto:mail@nexd.app)More information about the project (German only, sadly): https://www.youtube.com/watch?v=0PmuLrq4HnoGitHub: https://github.com/NexdApp/nexd-backendThank you and stay healthy!

Submitted April 24, 2020 at 10:25PM by andre-stefanov

Temporary password for authentication library?

I have a project I've been working on for awhile, it has user authentication, so you log in, and you can join groups/create groups, and you can post bugs to groups, like a place to manage different project bugs sorta, and then you can claim a bug to work on, etc. As of right now I haven't done much with Authentication at all, just the base functionality is there. Like anyone can join any group, however I want authentication on that of course, I want a temporary password, like a cookie. You can use if given by like an admin of the group, sorta like how discord has the invite to group feature, where it gives you a temp generated key to get in. Any libraries or ways to go about this easy? I saw Passport.js earlier?

Submitted April 24, 2020 at 09:44PM by Haunt626

Is it okay to share a function between two functions that are being called by API endpoints in NodeJS?

I tried searching about this but could not find a concrete answer. Is it safe to share functions within a NodeJS application?Lets say I have two API endpoints in a Node/Express app -// API endpoint 1. app.get('/endpoint1', function(req, res) { funcA(req.param, function(resultObj) { res.status(resultObj[0]).send(resultObj[1]); }); }); // API endpoint 2. app.get('/endpoint2', function(req, res) { funcB(req.param, function(resultObj) { res.status(resultObj[0]).send(resultObj[1]); }); }); The above endpoints are calling their respective functions (funcA and funcB) and each function call is being passed a callback which is responsible for responding to the client.Now if I have a third function (funcC), which has functionality common for funcA and funcB, can I have the two functions use funcC without any conflicts? Example -// Function A function funcA(param, callback) { // do something funcC(someParam, callback); } // Function B function funcB(param, callback) { // do something funcC(someParam, callback); } // Function C function funcC(param, callback) { // do something callback([200, 'Operation was successful!']); } Is the above logic safe assuming that any global variables being used are static? Would there be any issues if the "do something" part was making REST calls to another server?My reasoning that the above implementation would not be problematic is because I'm passing along the callback with the response object when making these function calls, so I'm assuming that the request and the response are "tied" this way. Is this correct?If multiple API endpoints are being served by a NodeJS application, does Node do anything to avoid race conditions like in a DB or is the developer responsible for avoiding such scenarios?Any other information regarding this would be really helpful.

Submitted April 24, 2020 at 09:01PM by mowgli1703

So what's the easiest best solution for deploying NodeJS app with socket.io and cronjobs to multiple servers?

I don't know if the title is the best way to ask the question and I can see how it can be a little confusing, but what I'm asking is that:I have a NodeJS app that uses socket.io to communicate with some clients and the clients being able to communicate with one another (through the server of course) and I want to deploy my NodeJS app to multiple servers to do a load balancing but keep the sockets working no matter the server that handles the request...In addition to that I have multiple cronjobs (cronjobs are dynamic, I have a cronjob for each user and on server start I start iterating through the users that need a cronjob running and start running it for them, also users can make a POST call to my public API with their token and start / destroy their cronjob...) the cronjobs are running every second and checking if there's data (belong to their user) in a certain table in MySQL DB and if there's then it transform it in a certain way and put it in a new table and removes the old row from the previous table, and I want to make sure the if I do a load balancing then my servers are not gonna both perform the same cronjobs twice or even more times for each user, which will make it create duplicate content in my DB..I'm using the cronjob npm for the cronjob operation...I'd love to get a link to a tutorial or an article that covers how to deploy my NodeJS app to NGINX or something for someone who has never done load balancing for their NodeJS apps, all while keeping the socket.io working and preventing certain cronjobs from running multiple times..

Submitted April 24, 2020 at 08:07PM by s_trader

Intraview - Platform which will help you to prepare for your interview

https://www.intraview.co

Submitted April 24, 2020 at 07:56PM by ziishaned

ES Modules or CommonJS for handling Modules across the Codebase?

I am setting up a Node.js (12.16.2 LTS) Backend and was wondering as to the following:Should I go with ES Modules (import & export) or CommonJS (export & require) way of handling my modules?Will I see any or have any advantage of using one over the other?Is going via the experimental feature the optimal choice over the long used one?Does 12.16.2 LTS support it without the experimental flag? As far as I understand, it requires the separation in the form of .mjs or .js file extension, or, by passing the experimental flag.I am comfortable enough with the CommonJS way of handling modules, but would like to explore any possible advantages of using ES Modules over CommonJS.What I read so far :Dynamic loading of modules is supported in CommonJS. But ES Modules allows pre-parsing of the modules and thus can enable in tree-shaking (not eyeing for anyway).Syntax matches with the famous frontend frameworks (not a worthy point for me).

Submitted April 24, 2020 at 07:23PM by rchougule

Start with lambda functions

Hi guys, I've done some small tests with lambda functions on AWS and it's amazing how everything works, I would like to start a project in an organize way: with a repo and a coherent structure but I don't know how to get the coherent structure, do you have any clue?In my head, I would like to have something like a monorepo or structure with every lambda function in a folder, with all their dependencies in their packages.json or similar, having some order, do you know any scaffolding, project in order to get that? Also it would be glad some CI to deploy with "no effort".

Submitted April 24, 2020 at 05:49PM by Fran_29

Delaying test

I have a Express server that connects to a db and i want to test a endpoint. How can i delay the test until server had stablish connection with the db?Thanks for the help.

Submitted April 24, 2020 at 04:21PM by Xiercoles

What does this mean?

const {parse} = require(“querystring”};

Submitted April 24, 2020 at 04:27PM by DagmawiBabi

From PM2 to Docker: Cluster Mode

https://maximorlov.com/from-pm2-to-docker-cluster-mode/

Submitted April 24, 2020 at 04:15PM by _maximization

Does anyone know how to validates forms without using third party modules?

No text found

Submitted April 24, 2020 at 03:37PM by DagmawiBabi

How to properly implment CSRF protection for a node and react setup?

I am having trouble with finding a way to properly implement CSRF protection. For node I have addedapp.use(csrf({ cookie: true, value: (req) => (req.cookies.csrfToken) })); and for react Im using axios to fetch data from server. How can I set header for CSRF for every type of request? and can I use an axios interceptor for setting headers to all requests or do I need manually set axios route in react app for CSRF?

Submitted April 24, 2020 at 03:11PM by silenf

How to install Node.js on Mac OS X

https://youtu.be/75nV2jhHSUY

Submitted April 24, 2020 at 01:19PM by AllInOneForEveryone

Pass package.json commands from a js file [Question]

I am working on a node.js native addon. While building for 32bit and 64 bit I have to set two different command for two different field.for 32bit"scripts": { "install": "cmake-js compile cmake -G \"Visual Studio 16 2019\" -A Win32" }, "cmake-js": { "arch": "ia32" }, for 64bit"scripts": { "install": "cmake-js compile cmake -G \"Visual Studio 16 2019\" -A x64" }, "cmake-js": { "arch": "x64" }, How can I set both cmake-js field and install field appropriately with a single command or Is their any way we can pass these command from java-script file.I want something likenpm run install32bit / install64bitwhere install32bit/install64bit is js files...

Submitted April 24, 2020 at 12:40PM by ptah_chaser

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

TL;DR - free copy, unlimited claims, for three days. Stay home and learn something new! <3Why 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/561q1y6htqu41.png?width=2252&format=png&auto=webp&s=8229ddfb55b11141052eeff012ec93f48d081b0aToday, 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=RDD_FR_2020_APRILIf you wish to purchase the course anyway, please use this link. You do not have to do this.Feel free to send the coupon out to any Juniors or students who might need it.#spreadtheknowledge #keeplearning

Submitted April 24, 2020 at 11:29AM by WeinAriel

Oraios Queries a new query builder

a light-weighted project aims to provide class-based table representation and flexible query experience to help developers to avoid plain string queries that are error-prune.CRUD Ops: Insert, select, update & delete Data from Postgresql and MySQL with flexible nested WHERE conditions.ORM: Create class-based models for your tables with built-in features.Flexible Queries: Designed to perform flexible, nested WHERE statements, ordering and grouping.Model Settings: Specify certain fields to be selectable, allow HTML tags to be stored in database for certain fields, add default values on insert and update, and more.Pre-defined Query Executers: Extract data in various ways: list, select one column, first item, slicing, chunking, pagination and more.Light Weighted: This package is light and can be added on APIs, web workers, .. etc.Check out my new query builder npm package and let me know what do you think.https://www.npmjs.com/package/oraios-queriesYou can check the docs here: https://medsaad.github.io/oraios-queries/index.htmlOr review code and add issues on github repo here: https://github.com/Medsaad/oraios-queries

Submitted April 24, 2020 at 11:07AM by MedzSd

Jest testing order inside a single testing file

Here's my testdescribe("bookmark route test", () => {describe("GET => /api/bookmarks", () => {it("should work", async () => {const response = await request.get("/api/bookmarks");expect(response.status).toEqual(200);expect(response.body).toHaveLength(0);});});describe("POST => /api/bookmark", () => {it("should create bookmark", async () => {const response = await request.post("/api/bookmarks").send({name: randomStr(randomInt(5, 12)),criteria: {searchWord: randomStr(randomInt(5, 12))}});expect(response.status).toEqual(200);});it("shouldn't create bookmark for invalid criteria", async () => {const response = await request.post("/api/bookmarks").send({name: randomStr(randomInt(5, 12))});expect(response.status).toEqual(400);});});describe("DELETE => /api/bookmark", () => {it("should not work for non-existent bookmark", async () => {const fakeId = randomId();const response = await request.delete(`/api/${fakeId}`);expect(response.status).toBe(404);});});});Will the first describe block run before the second and then second and so on or is it random?

Submitted April 24, 2020 at 09:05AM by undo124455

SO Help on overriding controller's swagger attribute

Hi everyone,I need your help with this overriding reusable controller's swagger description using decorators.https://stackoverflow.com/questions/61394012/override-swagger-attribute-in-a-reusable-controller

Submitted April 24, 2020 at 09:11AM by ark485

req.body return no data on XHR form submit

I'm trying to make XHR post request to my node app but req.body isn't returning anything.Frontend code: ``` ```Backend code: app.post('/admin/post/new',(req,res) => { let t = req.body.title; console.log(t) // returns: undefined console.log(req.body) // returns: {} console.log(req.method) // returns: POST res.send('Saved'); }body-parse: app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: true }))But if I do normal POST request without XHR or fetch then form is submitted properly.

Submitted April 24, 2020 at 07:38AM by pverma8172

Anybody wants help on their project?

Im bored and i wanna help somebody, maybe it's dumb but i really looking forward to make friends with some of great developers in this thread

Submitted April 24, 2020 at 07:45AM by teronodyssey

Thursday 23 April 2020

What's Async Local Storage in Node.js v14?

https://www.freecodecamp.org/news/async-local-storage-nodejs/

Submitted April 24, 2020 at 03:33AM by CodePerfect

How to get all properties out of a request response object?

Why does JSON.stringify(response) not return all properties of the object?I tried this: https://stackoverflow.com/questions/18391212/is-it-not-possible-to-stringify-an-error-using-json-stringify/26199752#26199752onsole.log(JSON.stringify(response, Object.getOwnPropertyNames(response.timings), 4)) And I get even fewer properties than if I just run:console.log(JSON.stringify(response, null, 4)) What gives?How can I spit out every single property that response has to offer?

Submitted April 24, 2020 at 02:47AM by grumpyThrifter

RTC connection only works after second offer/answer?

Hello, I'm trying to get more familiar with Node, WebRTC, and socket.io, so I followed a tutorial on a quick video chat web app.I'll spare you the verbose code, but this diagram is how it's structured. Really put my heart into it so go easy on meThe issue is, when a "call" (function call to callUser(socketId)) is made from one client to another, it doesn't work the first time. As soon as a second "call" is made, the video feed displays as intended. Here is the code responsible for this functionality.Client:/* React to a call */ socket.on("call-made", async data => { await peerConnection.setRemoteDescription( new RTCSessionDescription(data.offer) ); const answer = await peerConnection.createAnswer(); await peerConnection.setLocalDescription(new RTCSessionDescription(answer)); console.log("Received call from " + data.from); // debug console.log("Sending answer...") socket.emit("make-answer", { answer, to: data.from }); }); /* React to an answer */ socket.on("answer-made", async data => { await peerConnection.setRemoteDescription( new RTCSessionDescription(data.answer) ); console.log("Received answer."); // debug }); async function callUser(socketId) { const offer = await peerConnection.createOffer(); await peerConnection.setLocalDescription(new RTCSessionDescription(offer)); console.log("Calling user: " + socketId); // debug socket.emit("call-user", { offer, to: socketId }); } Server:/* Call user */ socket.on("call-user", data => { socket.to(data.to).emit("call-made", { offer: data.offer, from: socket.id }); }); /* Answer user */ socket.on("make-answer", data => { socket.to(data.to).emit("answer-made", { from: socket.id, answer: data.answer }); }); Can anyone give some insight as to why this may be? Is it something I'm doing wrong, an error on my network, or just a fact of life that I'm not aware of? Thanks!

Submitted April 24, 2020 at 12:14AM by zDev19

What happens after you install a package using `npm install`?

Hi everyone, im new to node.js and i’ve been trying to learn three.js. My question as the title says is what happens after i install a package? I created a project but i cant comprehend how does that package can be referenced in my javascript code. So in that case, what is the purpouse of globally installed packages? Should i install them locally to my project folder so that i can use them? Sorry if this seems very silly but i dont know where to ask and im having trouble understanding the resources online. Thankss

Submitted April 23, 2020 at 11:28PM by rogerpeke97

Recieving error when running child Process to run shaka packager

I am trying to learn how to chain commands together using child processes. Trying to utilize shaka packager to create dash mpds.Now at the cp.exec function if I runcp.execSync('cd scripts/src/out/Release/ && ls', exec_options); it shows the contents in that directory. But there is the packager.exe file I am trying to run, when I use the below codecp.execSync('cd scripts/src/out/Release/ && ./packager --help', exec_options); I get the error:'.' is not recognized as an internal or external command, operable program or batch file. { Error: Command failed: cd scripts/src/out/Release/ && ./packager --help '.' is not recognized as an internal or external command, operable program or batch file. ​How do I use the ./runafile syntax using a child process?​const cp = require('child_process'); const makeMpd = async function(videoUrls, req, res) { const exec_options = { cwd: null, env: null, encoding: 'utf8', timeout: 0, maxBuffer: 200 * 1024 }; try { let data = cp.execSync('cd scripts/src/out/Release/ && ./packager --help', exec_options); console.log('#2. exec sync'); console.log(data.toString()); } catch (err) { console.log(err); } }

Submitted April 23, 2020 at 09:38PM by bankfraud1

Why I love duck-typing

When I am close to forget why I love node.js then a challenging task that would be impossible to do in any other language, reveals trivial on node/js.Today I was configuring a gulp pipeline that has to use an external library. Everything works fine except on watch mode, because the library starts an http server and if I try to run it again I will get a port in use error. Such lib doesn't expose the created server at all, so what I did? You said it, duck-typing!! I mock the http create server function in just 3 lines of code:javascript const http = require('http'); const _creates = http.createServer; let twServer; http.createServer = function createServerMock() { twServer = _creates.apply(http,arguments) return twServer }Then my gulp tasks become trivial!!!``` function stopAnyRunningServer(cb) { if(!twServer) return cb() twServer.close(cb) }function serve(cb) { externallibrarycommand('--server','8087') cb() } ```No need to spawn processes, no need to use nodemon or any external library, just plain node + gulp

Submitted April 23, 2020 at 07:33PM by danielo515

Question regarding DI and node

I've heard a lot of times that DI is sort of overkill for node because you can just export a function? What does this mean exactly?

Submitted April 23, 2020 at 07:00PM by spermlung

13 Security Tips for Front-End Apps

https://medium.com/better-programming/frontend-app-security-439797f57892

Submitted April 23, 2020 at 05:45PM by denomer12

GitHub Action that syncs repository description, homepage and topics with package.json

https://github.com/marketplace/actions/sync-package-json-with-repo-info

Submitted April 23, 2020 at 04:48PM by Jaidchen

Passport js question

I am trying to make a user authentication system with Passport. I used this github repository, and everything seems to work except the code below. When passport is finished authenticating (done callback from users.js route is hit) the successRedirect isn't happening. However when I kill the server the success page loads in the URL. Can anyone tell me what I can do to solve this router.post('/login', (req,res,next)=> { passport.authenticate('local', { successRedirect: '/dashboard', failureRedirect: '/users/login', failureFlash: true })(req,res,next); }); Thanks for your help!

Submitted April 23, 2020 at 04:33PM by doesntspank

5 Mistakes Web Developers Should Avoid When using JWTs for Authentication

https://www.ducktypelabs.com/5-mistakes-web-developers-should-avoid-when-using-jwts-for-authentication/

Submitted April 23, 2020 at 03:50PM by ducktypelabs

Book for beginner

I'm starting a side project based on Node. My main language has been Java so almost no JavaScript language knowledge.I was looking for some books recommendations.Thanks in advance.

Submitted April 23, 2020 at 03:13PM by Xiercoles

Directed graph visualiser recommendation s

Anyone got any recommendations for a good package that can draw a directed graph on screen?

Submitted April 23, 2020 at 03:16PM by K9Morphed

Puppeteer crawled product name includes " char (inch), how escape it...

Hello node.js and reddit community.I have one weird issue, at least I think that's whats causing the issue... I'm building an automator which syncs b2b with my ecommerce, and with monitors name it comes to an issue.Here is an example monitors name: Monitor 18.5" Acer V196HQLAb LED VGASo, inside some of the page.evaluate functions, I use:const qs = sel => document.querySelector(sel) const nameRef = "h1.name" const name = qs(nameRef).innerText // name === "Monitor 18.5" Acer V196HQLAb LED VGA" Now this issue only occurs with monitors, and specificaly the name AND specificaly when the bot tries to push the generated product to the MongoDB so I figured it must be where the error occurs.​Any ideas how I can solve this problem? Would something simple like .replaceWith('"', '\"') do the trick?​Thanks!!

Submitted April 23, 2020 at 12:56PM by mmPvEhunter

How to make redirect from url like this - example.com///// to example.com/ in nuxt.js?

Hi there!I have a project on nuxt.js which I deployed to Google App Engine and I need to make redirect from url with more than one slash at the end to url without repeating slashes. I searched a lot but nothing helped. My backend is php, so I can't use express.js plugins.How can I do it in nuxt.js?Thanks in advance!

Submitted April 23, 2020 at 01:15PM by IgorOleniuk

Accessing remote machine over SSH

Hi, I'm doing automation testing using protractor. For one of the tests I have to run a few commands on a remote VM. I'm trying to achieve this by using SSH. I've tried using simple-ssh, remote-exec and ssh-exec. The problem is that my code runs without throwing any errors but the commands that I'm trying to run remotely are not executed and I'm pretty sure that SSH is not logging on to that machine as well.Any pointers is appreciated, I'm pretty new with this, so, sorry if this sounds stupid.

Submitted April 23, 2020 at 11:26AM by Strike_Reaper

Video Course Downloader I made with Node and Nightmare

https://github.com/JamieNichols/PacktPub-Video-Downloader/

Submitted April 23, 2020 at 12:15PM by jamie337nichols

OneTesselAway: Building a Real-Time Public Transit Status IoT Device

https://medium.com//onetesselaway-public-transit-status-iot-device-70b80ab8475b?source=friends_link&sk=1f696d85e6cb1d114c0fcd7b92cb5a28

Submitted April 23, 2020 at 09:16AM by Fewthp

Angular admin template integrated with Node.JS backend and PostgreSQL database

https://www.producthunt.com/posts/sing-app-angular-node-js

Submitted April 23, 2020 at 08:54AM by ZestycloseChocolate

Build a Flush Message Middleware with Node.js from Scratch

https://medium.com/@pkoulianos/build-a-flush-message-middleware-with-node-js-from-scratch-843f6e9823ba

Submitted April 23, 2020 at 07:49AM by pkoulianos

Wednesday 22 April 2020

How to test basic API with curl?

I have an index.js and queries.js set up on my Express API on ec2. I'm 90% sure my queries.js is set up correctly.This is the contents of my index.js: https://pastebin.com/i5Ess9LXHow would I go about testing -- I guess with the curl command first -- whether the getUsers etc. commands work correctly?curl myec2url.com:3000/getUsersSomething like that?

Submitted April 23, 2020 at 06:07AM by LevelChart8

Question about testing.

So i am learning about testing with jest and supertest and i have a question.I am testing my /api/bookmarks routes and i was easily able to test GET and POST. however to send a DELETE request i need the document's id to delete it.how do i do it? should i send a post request and get the id from response or would that go aganist unit testing philosophy?I am still new to node and i appreciate any help or advice.

Submitted April 23, 2020 at 03:55AM by undo124455

👨‍💻💻 Node.js 14 release explained | What you need to know as a developer

https://youtu.be/JxCV0l3N9uE

Submitted April 23, 2020 at 01:20AM by vladwulf

Light and blazingly fast caching utility utilizing Redis - includes Express middleware

https://github.com/eddiejibson/cachi

Submitted April 22, 2020 at 10:19PM by m1screant

Does anyone know how to check this? I’m on MacOS and just download NodeJS 14 (really excited!)

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

Submitted April 22, 2020 at 09:35PM by McQuillus23

Weird behavior with AWS SDK when running from a Electron app that was compiled to an EXE file

Hey guys, i've been working on an application in Electron for essentialy uploading/downloading files from AWS S3, and I have run into a bit of a strange issue. While I was testing my application, it was able to upload/download files from AWS S3 with no issue, but after building and packaging it into an excecutible file, it does absolutely nothing when it goes to upload the file. No errors are thrown, either, but it just does not upload the file and the promise never resolves. Any ideas? You can find my repo here: https://github.com/kkingsbe/Aurora-Multiplayer-Client

Submitted April 22, 2020 at 07:06PM by kkingsbe

Testing in AdonisJS

So, I work with adonis, and our tests are kind of a mess. They don't take advantage of transactions to clean up after each test, nor do they use any of the builtin traits. Documentation seems sparse on the subject, so what im looking for is tips and tricks for working with tests in adonis, if anyone out there has experience with it.Specifically, what Id like right now is to know the correct way of setting up a few default objects in our database before running a bunch of tests (we currently use the before and after hooks for this, but Im kinda sure there is a better option). Is setting up a Trait the way to do it? Attach the created stuff to the Context?

Submitted April 22, 2020 at 07:27PM by JulioCaye

5 Git Tools That Require No Coding

https://overflowjs.com/posts/5-Git-Tools-That-Require-No-Coding.html

Submitted April 22, 2020 at 06:40PM by denomer12

HTML in Node.js?!

https://ckeditor.com/blog/html-in-node-js/

Submitted April 22, 2020 at 07:00PM by norwegianfisherwoman

Node.js Version 14 Available Now! | New Features of Node.JS | Node.JS 14

Here's a video on the new features of the new version of Node.JS v14Node.JS v14Do Watch: Node.js V14 is here!We’re excited to announce that #Nodejs14 was released today! Node.js 14 replaces Node.js 13 as our current release line Node.js 14 will be the `Current` release for the next 6 months, and then promoted to Long-term Support (LTS) in October 2020. r/node r/nodejsNow, It’s the best time to start testing applications with Node.js14, and try out new featuresAs a reminder — both Node.js 12 and Node.js 10 will remain in long-term support until April 2022 and April 2021 respectivelySo, let's get started...Diagnostic Report goes StableV8 upgraded to V8 8.1Experimental Async Local Storage APIStreamsExperimental Web Assembly System InterfaceRemoval of Experimental Modules WarningNew compiler and platform minimumsCall to actionFinal WordsThis release line is perfect for trying out the latest features, testing the compatibility of your project with the latest Node.js updates and giving us feedback so that the release is ready to transition to LTS in October. #releasenodejs14 #newfeaturesofnodejs

Submitted April 22, 2020 at 06:01PM by ginny_smith