Tuesday 31 March 2020

Syphon module in nodejs?

Is there a module for macOS's syphon video? Or a way to livestream to an RTMP server?

Submitted April 01, 2020 at 02:38AM by BoredInopportuneness

Made a site to sell Yu-Gi-Oh (and eventually Pokémon and MtG) using Nodejs

http://kardkartel.xyz/

Submitted April 01, 2020 at 12:06AM by OP_IS_A_LEGEND

What is the best way to simply stream comments from Reddit?

I want to stream comment data from reddit in real time. My problem is this is my first project that I will be trying to update something on the fly as opposed to just sending and receiving request one at a time. If you were to do this what libraries would you use to keep it as simple as possible?

Submitted April 01, 2020 at 12:33AM by TheSlothJesus

Webpack Aliases with Webpack Merge and Eslint Import Webpack Resolver

Hello everyoneMy eslint doesn't recognize my local modules (webpack aliases). Normally this should be done with the eslint-import-resolver-webpack package but I'm pretty sure it doesn't work because of the way my webpack is build. I'm using webpack merge.. The eslint-webpack-resolver plugin looks for a webpack config file, I feel like it can't read the aliases..Mind you, everything works my project can build. It is just eslint not recognizing my modules.Does anyone have a solution for that?here are the complete files:- https://hastebin.emielvanseveren.be/turanetifo.js (webpack.config.js)- https://hastebin.emielvanseveren.be/icocogibom.js (webpack.parts.js)- https://hastebin.emielvanseveren.be/fonemazado.js (.eslintrc.js)​example of the error.eslintrc.jsWebpack aliases (webpack.parts.js)

Submitted April 01, 2020 at 12:36AM by emielvanseveren

Move file from external server to AWS

I think that at the beginning I should mention that I'm not using plain node, I'm using nest.js which is based on express but with Typescript.I have an external service which creates audio files for me and return an URL at which I could access the files. After the creation of the file I want to move them over to an AWS S3 Bucket to store them together with other corresponding file. With multer I got it working that when I send a POST request with an file from my local machine to a specific endpoint, the request gets redirected directly to AWS. But I don't found any usefull resources to make the whole thing working with an request made by my server except downloading the file to my servers filesystem and upload it again.Does anyone know a better solution for my problem ?

Submitted April 01, 2020 at 01:18AM by huthlu

Good resources for Unit Testing

Any good resources (tutorials, courses, website, books...) to get into unit testing for NodeJs using mocha, chai? Im beginning to use NodeJs and need to understand the basics of the unit testing using mocha and chai as well as sinonJs Something like code craft for Angular will be amazing

Submitted April 01, 2020 at 12:14AM by Jerbz96

Myzod: Schema Validation and Type Inference Package

/r/typescript/comments/fsew7n/myzod_schema_validation_and_type_inference_package/

Submitted March 31, 2020 at 04:28PM by davidmdm

ERROR: Failed to download Chromium r624492! --- appeare when I start ndb

​Faliled to download chromium when I start ndb. Can you tell me how can I fix this ? I am running Linux Mint

Submitted March 31, 2020 at 03:13PM by abig0

Pain points in MERN backend testing?

What are some pain points in MERN backend testing that you all are experiencing? For us, Jest/supertest helps for basics of unit testing and integration, but trying to test all inputs against resulting outputs seems to require a lot of manual coding. Curious about others' thoughts & approaches.

Submitted March 31, 2020 at 03:01PM by thinkinglemon

Knex.js migrations, does each table has its own migration?

Im currently learning Knex.js and try to create a basic todo REST API.I have these SQL tables here``` CREATE TABLE IF NOT EXISTS users ( id INTEGER AUTO_INCREMENT, name VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, role_id INT, PRIMARY KEY(id) );CREATE TABLE IF NOT EXISTS todos ( id INT AUTO_INCREMENT, todo VARCHAR(255) NOT NULL, done BOOLEAN NOT NULL DEFUALT false, FOREIGN KEY (user_id) REFERENCES users(id) ON UPDATE CASCADE ON DELETE CASCADE, PRIMARY KEY(id) ) ENGINE = InnoDB; ```How would I go about implementing them with Knex.js migration? Does each table have its own migration file, like: knex migrate:make create_users and knex migrate:make create_todos or should it only be on a project level like knex migrate:make create_tables?And what if i now have two migration files, would the command knex migrate:latest only take the latest file timestamp based, or include both tables based on the name?

Submitted March 31, 2020 at 03:02PM by Tanckom

Analytics / admin tool

Hello everyone!I wanted to get your opinion on analytics or admin tools for your Node app..The thing is that I have a Node app running Express and MongoDB. And I would love an easy and reliable way of checking simple stats, like user signups and other database entries.Coming from Python Django there is a build in admin that will help you get a quick overview of your site, as well as performing simple CRUD operations.Is there any pre built solutions out there? Or should one build an admin page themself?I would love to hear what you do (:

Submitted March 31, 2020 at 12:16PM by Maltmax

Notifications system using PHP + Socket.io + MySQL

So, I'm looking to implement a notifications system, as well as chat messaging later on into an existing project where the technologies used cannot be changed (as we're quite a bit into development). This is a newbie question as I started looking into this functionality just yesterday.MySQL database contains a table called notifications which gets updated in certain functions in the php controller. I add an entity, other users get notified of it.I've thought about a few approaches:First one I've thought about is listening to the changes of the mysql 'notifications' table... Is this possible? A few online posts say that listen/notify is not possible with mysql. This would be my preferred way of doing this since it seems the easiest and the least complex.The controller function inside php sends data to the node socket and everything gets updated immediately. However, I'm using php phalcon, and I haven't figured out a way yet to do this. I reckon there's an universal php implementation for this maybe, but I haven't found it.Also, I'm open to using something other than socket.io if it gets things done in an optimal way.I'd appreciate help if anyone has run into the same problem! :) Cheers

Submitted March 31, 2020 at 12:13PM by bringmeteaorcoffee

Error in installation in npm help me out

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

Submitted March 31, 2020 at 11:23AM by Aeinp-jerry

Node JS Discord Server ?

I was wondering if anyone here has a valid link to any Node.js Discord Server, I've Googled and searched reddit I couldn't find anyone, the few links I found are no longer valid. I found discord quite interactive with close to immediate response to questions/problems, I really will appreciate if anyone could help me with a valid link.Thanks.

Submitted March 31, 2020 at 11:29AM by eazylaykzy

Node.js/Express little project!

Hi everyone!I just started learning Node.js/Express and MongoDB, so I wanted to show a little project I have made as a part of the course I am currently doing, where you can share your secrets anonymously!Repo: https://github.com/AbayIbrayev/SecretsApp#readmeLink: https://sharesecrets.herokuapp.com/The app is using Passport.js and Google OAuth 2.0 for authorization and deployed on Heroku! I would love all your feedback and maybe some suggestion!Thank you all!

Submitted March 31, 2020 at 12:02PM by abaydev

Sequelize with asynchronous configuration in nodejs

I have been bashing my head for days as I cannot find a valid example of async configuration in Sequelize.So as you may know, you can simply config a Sequelize instance like thatconst sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname') and then declare your Modelconst User = sequelize.define('User', { // Model attributes are defined here firstName: { type: DataTypes.STRING, allowNull: false }, lastName: { type: DataTypes.STRING // allowNull defaults to true } }, { // Other model options go here }); However what happens when the db credentials comes from an external service?const credentials = await getDbCredentials(); const sequelize = new Sequelize({credentials}) since sequelize models creation are coupled with the instance creation (unlike many others ORMs) this becomes a big problem.​My current solution is the following:const Sequelize = require("sequelize"); // Models const { User } = require("./User"); const env = process.env.NODE_ENV || "development"; const db = {}; let sequelize = null; const initSequelize = async () => { if (!sequelize) { let configWithCredentials = {}; if (env === "production") { const credentials = await getDbCredentials(); const { password, username, dbname, engine, host, port } = credentials; configWithCredentials = { username, password, database: dbname, host, port, dialect: engine, operatorsAliases: 0 }; } const config = { development: { // Dev config }, production: configWithCredentials, }; sequelize = new Sequelize(config[env]); sequelize.authenticate().then(() => { console.log("db authenticated") }); }); } db.User = User; db.sequelize = sequelize; db.Sequelize = Sequelize; }; initSequelize().then(() => { console.log("done"); }); module.exports = db; ​However I feel that this is not a good approach because of the asynchronous nature of the initialization and sometimes the `db` is undefined.Is there a better way to approach this thing?Thanks

Submitted March 31, 2020 at 10:26AM by madeo_

How to deploy it to my own server?

I have my own domain (let's just say www.example.com). I also have a nodejs app. I want to run it at www.example.com/mynodeapp/. How do I do this if I also want to have another node app for insane at www.example.com/anothernodeapp/ ? Thanks!

Submitted March 31, 2020 at 08:48AM by PaulGrasser

Why is the code below if state executing even though I returned res.end();? Shouldn't it end the function? (I'm a noob so i lack basics)

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

Submitted March 31, 2020 at 08:56AM by Sparsh_Joshi_42

Monday 30 March 2020

Multiple pages in node.js website???

I want to know if it's possible to have multiple pages (I saw a folder named pages in an ad so that's where this came from or from some place maybe a blog youtube but I knew it was node.js because there was a file named blank.js)

Submitted March 31, 2020 at 05:14AM by Juls0730

Block.io Account Creator in Node.JS

https://twitter.com/triidnt/status/1244838787349348355?s=21

Submitted March 31, 2020 at 05:22AM by Diivinus

Can't access image from PUT request

I can't seem to figure out how I can access the image which is being sent in a put request using nodejs. At the moment I'm am using fs.writeFile:exports.uploadPhoto = async function (req, res) {fs.writeFile(fileName, req.body, 'binary', function (err) {if (err) throw err;respond(res, 200);});}However if I check the length of req.body it says its 0 and it writes 0 bytes to the file. In the bodyParser I have:app.use(bodyParser.json());app.use(bodyParser.raw({ type: 'text/plain' }));app.use(bodyParser.raw({ type: [ 'image/jpeg', 'image/gif', 'image/png' ], limit: '20mb' }));The body type I am using in postman is binary with an image attached. I am really confused as to what is going on. Any help would be greatly appreciated.

Submitted March 31, 2020 at 04:10AM by personalfnzthrowaway

New YouTube channel for Software Development Tutorials and Practices. Feedback Appreciated 😄

Channel Link : https://www.youtube.com/channel/UCOLlYtqmBbc37DuP5CY0qwA1st Video : Learn How to Build a Simple Web HTTP Proxy with Plugins as Middleware - https://youtu.be/JkY0ANDx1dU.GitHub : https://github.com/rchougule/NProxy2nd Video : Why are EventEmitters Important? Understand with Visualisation and Implementation https://youtu.be/AuNKvV-rVUE

Submitted March 31, 2020 at 04:55AM by rchougule

Did you ever leverage Node's ability to dynamically load an external C or C++ DLL file at runtime and utilize its API to perform some operations written inside it from a JavaScript program?

Did you ever leverage Node's ability to dynamically load an external C or C++ DLL file at runtime and utilize its API to perform some operations written inside it from a JavaScript program? Why did you do it and how did it benefit your application? I am really curious.

Submitted March 31, 2020 at 03:16AM by jasonscript

Need some help with authentication

Hey I am attempting to make the transition from a front end developer to full stack and I wanted to know if anyone could explain authentication and authorization conceptually, ("Alot of online articles, talk about oauth, passport.js jwt etc and I want to know what the basic process is in absence of some specified technology"). I know the basics such username, passwords, salting a password then hashing it but I confused as to why so many packages and libraries are needed in a production application. Any help would be highly appreciated.

Submitted March 31, 2020 at 01:30AM by Jeshmel97

Long-running process delaying promises

I have a process that runs for hours, and it has a callback every 1 percent, whose purpose is to send the new percent to the API so that the UI can track the progress.I know the callback is happening because I can see the percentage being console logged.But my promise to send out the new percentage to the API (using axios if that makes a difference) is delayed until the long-running process finishes. All 100 requests to my API go out at the same time, after the long process is completed.What can I do to ensure that my API request is actually sent out instantly, rather than delayed? Here's some pseudo code to clear up any potential confusion.longProcess.start({ onPercent: async percent => { console.log(percent); // I can see this at the right time (one every couple // minutes) await api.updatePercent(percent) console.log('done', percent) // All 100 of these get printed at the same // time. After the entire thing is done. } });

Submitted March 31, 2020 at 02:00AM by esreveReverse

How do I start learning Node.js

I worked a bit on Angular2 and python. Was looking into learning Node.js. Any good online resources/tutorials where I can start learning? Thanks in advance.

Submitted March 30, 2020 at 11:50PM by suhas070495

Some Useful Node.js Internal Modules

https://christosploutarchou.com/some-useful-node-js-internal-modules/

Submitted March 31, 2020 at 12:19AM by cploutarchou

A question for NestJS users

How do you decide what goes into a module, or when to make a module? I've just started my first project and I'm using TypeORM, and I feel like it'd be too easy to essentially end up just having a module per entity, I'm guessing that's a bad way to do things though right?

Submitted March 31, 2020 at 12:21AM by -100-Broken-Windows-

Covid 19 API & Auto Updater in NodeJS/Docker.

Recently I made a scraper for Covid 19 to save the data in a MySQL database, and with this, I made an API to recover the data in JSON format.​To maintain always to update the data this scraper runs with a cron every 12 hours, this time can be edited via env variables.​Right now it's published in the next link http://ec2-18-223-118-73.us-east-2.compute.amazonaws.com/​The endpoints are:/countries: http://ec2-18-223-118-73.us-east-2.compute.amazonaws.com/countriesthis endpoint supports a country and a date filter via query params `?country=NAME&date=YYYY-MM-DD` both can be used at the same time or each one by separated/worldwide: http://ec2-18-223-118-73.us-east-2.compute.amazonaws.com/worldwidethis endpoint supports a date filter via query params `date=YYYY-MM-DD`​You can find the repository here https://github.com/AndresMorelos/covid-19-apiI'm open to feedback, Issues and pull requests to make this app better.​​https://preview.redd.it/vyu6u03jewp41.png?width=1898&format=png&auto=webp&s=71bb93bed6e75f57c9e3b8d55d39410128c8c0cf

Submitted March 31, 2020 at 12:55AM by andresmorelos

Trying to understand class instances

I am trying to wrap my head around class instances and garbage collection.If I request a row from a database and store its fields in an object in memory, I understand that it makes most sense to use a new instance of a class to for example store user data in a user instance. My question is if I have multiple users using my app at the same time, and I create a user object for every one of them when they log into the site, how do I make sure the variable values in my function don't get overwritten by a new user instance that's using the same code while I'm waiting for an async operation to finish? And if that user object is then not in use anymore, how will the garbage collector now that it is not in use anymore if the code is still referencing that object from certain functions?

Submitted March 30, 2020 at 09:34PM by louissugar

A discord music bot with voice commands and more

Have you ever wanted to command your discord music bot using your voice? For years of using discord I secretly wanted to. A couple of weeks ago the engineer inside of me decided to act.I made my code completely open source so it is free for everyone to use, including a demo video: https://github.com/healzer/DiscordSpeechBotThis morning I had feedback from a guy who has hearing problems, and he wondered whether this tech could help him communicate better with his friends. So I quickly built a prototype for him and he was quite happy. Once again the code is open source and available on github: https://github.com/healzer/DiscordEarsBot

Submitted March 30, 2020 at 08:42PM by ilya47

Best way to build a docs site for an npm package?

HeyI have a React package I want to publish that, so it has a peerDependency on React.I also want to build an docs website, in the same repo.File structure will look like this:| - docsSite | - index.html | - app.js | - package.json (contains dependencies for React) | - src | - myPackage.js | package.json (contains only peerDependencies) app.js has something like this:import myPackage from '../src/myPackage.js' However, when running parcel inside /docsSite, React complains that there is 2 versions of React. I notice it has also updated the top level package.json (the one that belongs to myPackage) with a dependency for React.How do I overcome this? Or is it better to break off the documentation into it's own repo?Thanks

Submitted March 30, 2020 at 08:50PM by DonMildreone

Downloading file from URL

I am trying to download csv file from the response of a get request below:const axios = require('axios'); async function exports() { let initiate_export = await axios({ method : 'get', url: 'https://v3.synccentric.com/api/v3/products', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer API_TOKEN' }, data: { "campaign_id": campaign id, "fields":["asin","upc","parent_asin"], "downloadable": true, "downloadable_type": "csv" } }) return initiate_export } exports().then(async (res)=>{ await get_export.downloadExport(res.data.attributes.url) }) the function 'exports()' initiates the download process. I pass the returned information to the 'downloadExport' function provided below:​const Fs = require('fs') const Path = require('path') const Axios = require('axios') async function downloadExport (exportUrl) { const todaysdate = new Date(); const url = exportUrl const path = Path.resolve(__dirname, 'results', 'Results' + todaysdate.getMonth() + "-" + todaysdate.getDate() + "-" + todaysdate.getYear() + '.csv') const writer = Fs.createWriteStream(path) const response = await Axios({ url, method: 'GET', responseType: 'stream' }) response.data.pipe(writer) return new Promise((resolve, reject) => { writer.on('finish', resolve) writer.on('error', (error)=>reject(error)) }) } module.exports = { downloadExport } I keep getting the following results from downloadExport():{"errors":[{"status":400,"title":"Export job in progress","detail":"You will be able to download when the job is complete"}]} My question is, how do I call downloadExport, only when the file is finished buffering in the browser?The API im using doesnt provide a polling method for the status of the export.I know downloadExport() works because after several minutes i manually pass the 'res.data.attributes.url' to the function and the CSV download correctly.

Submitted March 30, 2020 at 08:51PM by cbassolympics

I'm trying to install node-gd via npm, but I get nothing but errors.

I'm trying to install node-gd on Raspbian via npm. When I try to run sudo npm install -g node-gd, I get this error:gyp WARN EACCES current user ("nobody") does not have permission to access the dev dir "/root/.cache/node-gyp/12.16.1" gyp WARN EACCES attempting to reinstall using temporary dev dir "/usr/local/lib/node_modules/node-gd/.node-gyp" gyp WARN install got an error, rolling back install gyp WARN install got an error, rolling back install gyp ERR! configure error gyp ERR! stack Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/node-gd/.node-gyp' gyp ERR! System Linux 4.19.97-v7+ gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild" gyp ERR! cwd /usr/local/lib/node_modules/node-gd gyp ERR! node -v v12.16.1 gyp ERR! node-gyp -v v5.0.5 gyp ERR! not ok npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! node-gd@2.0.0 install: `node-gyp rebuild` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the node-gd@2.0.0 install script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /root/.npm/_logs/2020-03-30T18_33_16_519Z-debug.log I made sure I had node-gyp installed by running sudo npm install -g node-gyp. I also tried the above command with --unsafe-perms. I also tried doing the answer here: https://stackoverflow.com/questions/42308879/npm-err-code-elifecycle. Still no luck. Any help?

Submitted March 30, 2020 at 07:47PM by RocketJumpingOtter

Pointer Compression in V8

https://v8.dev/blog/pointer-compression

Submitted March 30, 2020 at 07:27PM by ecares

Email-Templates: They look Completely Different and I have no idea why

I need to be able to send invoices over email, which is why I turned to npm email-templates. Now, when it shows me a preview it's exactly the way I want it. However, when I actually send the email and view the results, it comes with all of the content but the css is completely messed up. Here is the code used to send it ``` const Email = require('email-templates'); const nodemailer = require('nodemailer'); // ---- Content here removed for privacy (auth obj, testdata obj) ------ let transportInstance = nodemailer.createTransport({ service: 'gmail', auth })const email = new Email({ message: { from: auth.user }, send: true, transport: transportInstance })function invoiceEmail(custEmail, custInvoice){ email.send({ template: 'invoices', message: { to: custEmail }, locals: { companyName: custInvoice.invoicer.firstName, invoice: custInvoice } }) .then() .catch(console.error); } `` I am using Pug as recommended byemail-templates` and, as I said, it looks fine in the preview. I sent an email to both Yahoo and GMail to look for changes, but they were both a mess and identical in that mess.

Submitted March 30, 2020 at 06:17PM by sinithw

Mongoose populate() not working as desired

I have a PaymentCard and a User schema, and want to define an existing user's ID when creating a new PaymentCard record to link that specific card to a specific customer. It does create the PaymentCard document with the customer's mongoID, however querying with .populate() does not return any cards on any of the users, and return empty arrays on all users.My Customer Schema:const Customer = new Schema({ name: { type: String, required: true }, surname: { type: String, required: true }, alias: String, customerStatus: { type: String, enum: ['Regular', 'Valued'], }, discount: { type: String, enum: ['Fixed', 'Flexible'] }, email: String, phoneNo: String, cards: [{ type: Schema.Types.ObjectId, ref: 'paymentcards' }] }) module.exports = mongoose.model('Customer', Customer ) My PaymentCard Schema:const PaymentCard = new Schema({ owner: { type: Schema.Types.ObjectID, ref: 'customers' }, nameOnCard: { type: String, required: true }, cardNumber: { type: String, required: true, unique: true, minlength: 15, maxlength: 16 }, cardIssuer: String, cvc: Number, exp: { type: Number, } }) module.exports = mongoose.model('PaymentCard', PaymentCard) The two functions I use to register a new card and get a list of all customers:router.post('/addPayment', (req, res, next) => { jwt.verify(req.query.secret_token, process.env.JWT_SECRET, (err, decoded) => { if (decoded.user.role == 'Advisor') { PaymentCard.create({ owner: req.body.owner, nameOnCard: req.body.nameOnCard, cardNumber: req.body.cardNumber, cardIssuer: req.body.cardIssuer, cvc: req.body.cvc, exp: req.body.exp }) res.send('Registered successfully'); } else { res.status(401).json({ message: 'Unauthorised' }) } }) }) router.get('/getAll', (req, res, next) => { jwt.verify(req.query.secret_token, process.env.JWT_SECRET, (err, decoded) => { if (decoded.user.role == 'Manager' || 'Advisor') { Customer.find({}, function (err, customers) { res.send(customers); }).populate('cards').exec((err, cards) => { console.log("Populated User " + card); }) } else { res.status(401).json({ message: 'Unauthorised' }) } }) }); Can you see where my problem is?

Submitted March 30, 2020 at 06:17PM by Fizaraz

Coming from a J2EE world I was curious to know how Express connection limits were defined and monitored. Learn how I did it to track request spikes

https://medium.com/@mhilaire/custom-aws-cloudwatch-metrics-c04d490b51b1

Submitted March 30, 2020 at 06:10PM by hemixam

Building SaaS using node.js

Hi all,I'm trying to figure out the best way to write a SaaS site. The idea is to serve practice tests for qualifying/admissions exams like the MCAT and LSAT.I want to provide a test interface similar to the ones provided by the official companies. As well, I want to integrate code for cursor tracking and custom analytics. I expect that this type of project requires a lot of back-end server work, as well as databases for users, the tests, and their scores.Would node.js be amenable to this type of project? Or would I be better off using something like Python or Django?As you can tell, I'm pretty new to this - are there good resources on node.js specifically, or should I just be extra proficient in Javascript?

Submitted March 30, 2020 at 05:23PM by syrupflow

Node js and Google sign in

Hi everyone. I've never done any backend development before so I thought asking here would help a lot. Right now I'm working on a project that will use node and angular so I wanted to use google sign for the login and registration to ease my job. But I can't seem to find any concrete resources other than the documentation (https://github.com/googleapis/google-auth-library-nodejs). The deadline is pretty close so would appreciate any help!

Submitted March 30, 2020 at 05:39PM by gorkychocolate

NestJS, monoliths and project structure

Hey, I'm currently working on a complete rewrite of an e-learning web app for the company I work for. The first version has been done with pretty much only Express, while all the rest had been implemented without the aid of any framework/library. I wasn't part of the team during the first iteration, and the first problem I noticed when I got hired was the huge amounts of redundant, reused, non standardized chunks of code and patterns.Now that my role is to plan, coordinate and take part in the whole rewriting process and since using NodeJS is the only strict requirement I must fulfill, I'm guessing if NestJS could be the right candidate for the job, given that I've used the framework for some small projects and have gotten to love it, but my mind is filled with doubts and would love if any of you could help me sort some things out.The project is gonna be a big monolith, and this is not even questionable due to a number of reasons I really don't want to waste your time explaining (team size, experience, deadlines, etc..).The modular structure imposed by the NestJS is great to keep things clean, but I can't really imagine how could I "cleanly" get a monolith done with it. Imagine needing 4 subcontrollers (Web, Api, Admin-web, Admin-api) instead of one single controller per module. This would be pretty easy to pull off if modules could be structured in a tree-like form, but all I see in the guides are a bunch of modules existing on the same level, so I guess my best bet would be creating 4 controllers under the same module. Not very clean. NestJS's basic project structure is clearly great if you're going for a SPA on the front (get 1, maybe 2 Api controllers per module and you're done), but what about old-school backend-served Handlebars pages?Also, the courses hosted by the platform should have several activities included, like quizzes, tests, etc.. and they should be freely sortable and configurable by the course admins. I would implement each activity as a different module then have one generic activity module load the right activity-specific module based on a bunch of parameters. Would NestJS be able to handle this kind of dynamic structure?Clearly what I'm trying to find out is if the framework is capable of handling a big amount of deep modularity without going the microservice way or if I should stick to more close-to-the-metal-yet-battle-tested solutions like Express/Koa/Fastify to retain control over the project by implementing my own structural core logic.

Submitted March 30, 2020 at 03:03PM by _cappu

How do i send response back with node?

video + audio real time chat using socket io in node js

​Hi guys,I am trying to do a real-time video + audio chat and I want to use client-server approach not peer to peer (Education purposes). Now I can stream only the video using code bellow. I want to use the same approach to send audio as well to my server using sockets a then emit to all connected sockets. Maybe socket.io-stream library can help if so how can I easily implement it into my code bellow? Or is there a better solution? Thanks.David// client code let socket = io.connect(window.location.origin); const video = document.querySelector('video'); const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const img = document.querySelector('img'); const audiodata = document.querySelector("audio"); navigator.mediaDevices.getUserMedia({ video : true, audio : true }) .then(function(stream) { video.srcObject = stream; setInterval(function() { canvas.width = video.videoWidth; canvas.height = video.videoHeight; ctx.drawImage(video, 0, 0, canvas.width, canvas.height); const imageData = canvas.toDataURL("image/jpeg", 0.4); socket.emit('sendImage', { image : imageData }); }, 100); }).catch(error => console.error(error)); socket.on("getImage", function(data){ img.src = data.image; }) // server code let express = require("express"); let socket = require("socket.io"); const port = process.env.PORT || 3000 let app = express(); // static files app.use(express.static("public")); let server = app.listen(port, function() { console.debug(`listenning on port ${port}`); }) // socket setup let io = socket(server); io.on("connection", function(socket){ console.debug(`made socket connection with id ${socket.id}`); socket.on("sendImage", function(data){ socket.broadcast.emit("getImage", data); }); });

Submitted March 30, 2020 at 01:12PM by prois99

why is it important to use environment variables?

No text found

Submitted March 30, 2020 at 12:12PM by Sakalalaa

What are Your Reviews on Mosh's Node Course

First I know that many people are going to bash me for not reading the reviews given on that site. But I want an honest opinion from the one who has completed that course and how that course is better than other courses out there

Submitted March 30, 2020 at 11:12AM by Bilal009900

Any good tutorial on Knex.js, Objection.js, Express.js with NodeJS?

Tl;dr, my teacher tries to teach us a stack with Knex.js, Objection.js, Express.js, NodeJS and MySQL.Unfortunately, he fails to teach and is more confused by himself than we are about the meaning of life.Doing some google search, I can't find really anything useful (outside of the official documentations) about this stack, which then creates a second question, why does he even teaches us this stack if there not many resources out there?

Submitted March 30, 2020 at 10:14AM by Tanckom

I need some advice regarding the deployment process

I don't know if this is the right place to ask this. But I've never deployed an app before.I'm using Node/express/mongo and angular on the frontend, on the localhost each app runs on a different port. I have read that it's possible to deploy each one a different server(never knew that before). would you recommend that?And in my case, I'm making a small web app, so I don't want to pay money on it, or at least dont wanna pay much on it. I'm looking for some hosts that offer good services for free. and what I care about the most is email verification. Thank you

Submitted March 30, 2020 at 08:44AM by Sakalalaa

Sunday 29 March 2020

when user join website = console.........

I want to make it so when a user joins my website it will print Request received in the console I used to have the code for this but I purged my website and it looks so much better so yeah I need some help I might not respond as soon as I usually would as its 1 am where I am

Submitted March 30, 2020 at 07:34AM by Juls0730

I built a private social media site with no trackers and completely Ad-Free! Do check it out! Suggestions and Feedback will be helpful

https://igloosocial.com

Submitted March 30, 2020 at 02:51AM by Ashwin110

I made an npm package that helps you distribute your code, allowing you to scale up your applications

Hi! I was recently working on a project and needed to remotely execute something. I solved this by making a small package that would handle this, but realized that by making a few adjustments I could make it an easy tool to use when wanting to distribute your code in a microservice-like way.The premise is simple; you create some servers that can execute functions when requested, then you create a client that will request these functions to be executed. Hook up a load balancer in between them and you’re ready to scale up your appI hope some people will find use in this!The package can be found here: https://www.npmjs.com/package/ezrpc

Submitted March 30, 2020 at 01:06AM by timgfx

Is there a way to hide NodeJS code when deploying?

So long story short some people in my office has access to the production server hosting root login and I don't want them to be able to see the NodeJS code but I want the server to run regularly, is it possible to do such thing? (Beside the obvious solution of prevent anyone from just accessing the hosting root user and password)

Submitted March 30, 2020 at 01:25AM by s_trader

Scrape within a script tag

I am trying to scrape this user information when logged in.async function scrape() {const response = await axios("view-source:https://extrabutterny.com/collections/release-draws");console.log("response: ", response);const html = await response.data;const $ = cheerio.load(html);const res = $('

Invoke docker using nodejs express application

Hi Folks,I wondering if anyone has any experience in invoking docker from a nodejs express web app.For example, the app will have a button to run a docker and stop the docker. What kind of technologies are used to achieve this?

Submitted March 29, 2020 at 10:58PM by svbarh

Node app and mongo app db cloud deployment

Hello everyone, I have developed a nodejs app that uses mongo as a user db. Have never really deployed in the cloud with this architecture and need some suggestions. Thought about just leveraging Mongo Atlas but then would need another machine to deploy node. Thoughts/suggestions/best practices?

Submitted March 29, 2020 at 09:51PM by jsd2358

WebRTC to Mobile

Hey Guys, I was just messing around webrtc and successfully implemeneted Browser-to-Browser Video & Voice call, i was just wondering if there was possibility of calling to actual mobile mobile phone (Iphone for example) i started researching it and there were terms like PSTN, SIP and etc. but i could not see any actual implementation or demo with source code, i know it works since globfone can implement it, and i want it internationally, so is there any demo? (with source)

Submitted March 29, 2020 at 09:54PM by xxxxsomeguyxxxx

Understanding the use of process.env in a web app

I was looking at an example React site and somebody used process.env to get a token-like object. This token along with the person's username would then determine whether or not the person could access the site.From reading about process.env it's related to whatever setup/environment the user has on their system. So I was thinking process.env would do something to get the person's relevant token. However when examining the code further there's actually a Config file with a hardcoded token (so I assume it's the same for all users). In this case why use process.env?

Submitted March 29, 2020 at 07:29PM by furthacharm

API Endpoint in Express stops working after 7 requests

Hey all, I have a simple login form that works fine with Node, Express, and React. If I make around 8 requests that are wrong(correct username, wrong password) it stops working and I cannot login even with the correct credentials until I have restart the server. Take a look at my code, if you've had an issue like this before, please shed some light on how you fixed it.. Thank you! I thought it may be because I don't call res.send or res.end if the call is unsuccessful, but I tried adding that and the problem still persists. No error logging.users.post('/login', (req,res) => { User.findOne({ where: { email: req.body.email } }) .then(user => { if(user) { if(bcrypt.compareSync(req.body.password,user.password)) { let token = jwt.sign(user.dataValues, process.env.SECRET_KEY, { expiresIn: 1440 }) res.send(token) } } else { res.status(400).json({error: "User Does not exist"}) } }) .catch(err => { res.status(400).json({error: err}) }) })

Submitted March 29, 2020 at 06:23PM by CharliePrograms12

Minimalist dashboard to track COVID-19

I woud like to introduce a simple Node.js project that is linked to the coronavirus outbreak.I couldn't stay without building my own minimalist dashboard to track it. :)Therefore, here is what I came up within few hours today. https://mighty-springs-61867.herokuapp.com/I hope this situation will end soon.Project: https://github.com/simongjetaj(Any collaborator is welcome to take this to the next level.)

Submitted March 29, 2020 at 06:03PM by simon_gjetaj

Deploying to Heroku but receiving errors.

Currently I am facing two errors:Image not being found. My website loads but the icon image is missing. I have it in a public file in my project directory. The error is GET https://messageiab.herokuapp.com/icon.svg 404 (Not Found). In my html file I have this tag: My fetch request is not working. The error is packageHandler.js:24 POST https://localhost:3000/ 503 (Service Unavailable) :​fetch('http://localhost:3000/', {method: 'POST', header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }, body: encodedData}) .then((response) => { message.style.opacity = "100%"; message.style.width = "100%"; message.style.height = "100%"; icon.style.width = "0%"; icon.style.paddingTop = "0%"; loadingMessage.style.opacity = "0%" message.style.pointerEvents = "auto"; return response.json(); }) .then((data) => { document.getElementById("senderName").innerHTML = data.name; document.getElementById("response").innerHTML = data.message; }); Now I get that I have to change the fetch request from the local host but when I switch it to my domain https://messageiab.herokuapp.com/ it still returns an error.

Submitted March 29, 2020 at 05:58PM by TheSlothJesus

What is the correct use case for NoSql

There's a post gaining some traction asking about NoSql hate. Lots of people saying it has its use cases but 90% of the time your going to want a relational database. Not much actual discussion what those use cases are.I've been prototyping a personal project starting out with node & mongo for no other reason that it was straight forward. But that posts got me wondering whether I should be switching to postgres, cause I'm not that far in.So what are the right use cases for mongo or other NoSql databases??

Submitted March 29, 2020 at 04:32PM by ItsASamsquatch

git-gc - a cli tool to clean-up unused git branches

https://www.npmjs.com/package/@duylam/git-gc

Submitted March 29, 2020 at 04:00PM by duypl

Front end, Back end and CAS authentication.

I'm a coop student and I have been tasked with getting a concept up and running with modern technologies. Currently the company has about 10 different applications, 4 or 5 different frameworks, and with the front end and back ends bundled together in each application.In my concept I would like to use an express API back end and a Vue.js front end. Eventually if this works then the plan would be to convert every application to use the same framework. However, the company uses CAS to authenticate everything. Unfortunately, I don't how I would get both the front end and back end to authenticate using CAS.If I was just using a front end and a back end then the front end would send the back end the username and password and validate that. However, the back end doesn't know that information. It has data for each user but knows nothing about their passwords.I do know somewhat how CAS works. And I can get the front end authenticated. But how can I authenticate the back end for a specific user?

Submitted March 29, 2020 at 04:04PM by OhMyGodBeckyLooky

Render a react app with some states passed in

Hello all, I have a node express backend and react front end.Currently when user register the backend sends a link with a jwt to the email. What I want to achieve is when user click on that link, which would be a get request, the backend would send the static assets of my react app but with some states - on verification page and success/error. How would I go about doing this? Thanks!

Submitted March 29, 2020 at 02:40PM by b439988

Use node application to send JSON and html content

I can't find any good information about how to do following:I have an API, programmed in node, that sends JSON, for example to GET /users.Now, I want to send HTML if a user tries to open the GET /users via a browser. How am I supposed to do that?I thought about doing a subdomain for the API (api.domain.com/users) and a main domain for web requests. Do I have to write a complete separate back-end for both?Or can I send in one application different results? Like res.json({information}) for requests that aren't web based and res.render(some ejs file) for web content? What is the recommended way of doing something like this?(My goal would be to just run one heroku server, to minimize cost)

Submitted March 29, 2020 at 11:51AM by hertelukas

Need help choosing between .net and nodejs in my situation

/r/learnprogramming/comments/fqgvri/need_help_choosing_between_net_and_nodejs_in_my/

Submitted March 29, 2020 at 10:17AM by _asksillyquestions

Saturday 28 March 2020

Why so much hate for nosql ?

I wanted to know why does their seem to be so much hatred for mongodb ? I see alot of node js courses offering to teach it but users of node js w / express seem to hate ? Can any one explain why ?

Submitted March 29, 2020 at 04:00AM by Jeshmel97

Join Legislation Alert Project : needs node and react help

Do YOU want to Join a part time / fun project? Possibly a start-up in stealth mode.AI project with a Node middle tier and React front end needs you! Ping us.

Submitted March 29, 2020 at 02:30AM by sorinadrianr

What could be a good way to send out large data over sockets? (Socket.io)

I have a NodeJS socket.io server to bridge between two web clients. I want to send large data from one to another so I’m splitting it and sending it one piece at a time.It is great, and works, but it’s insanely slow. With that method I achieved a transmission speed of roughly 0.8mb/s locally.What would be a good way to transmit a large amount of data, quick and efficient?

Submitted March 29, 2020 at 03:01AM by TheNicestAF

I need help with a depcheck error

If I install depcheck globally it runs ok, but if I install it with --save-dev and then run npm run depcheck It finish with an error and I don't know why. Already clean node cache , erase node_modules folder and install everything again. Welcome any advice guys, thanks.https://preview.redd.it/qu0b6anmhip41.png?width=217&format=png&auto=webp&s=9e9c1259288ed4f91b75c95618f95e5a25630bc4​https://preview.redd.it/d6r8hmpphip41.png?width=631&format=png&auto=webp&s=0260a52eb210b1f0cb538697cc95991de13cfea6

Submitted March 29, 2020 at 02:09AM by MPB1982

What i need to know for get a jr developer job?

Hello, I want i job but i dont know if im able to get one I now how to create a crud, rest,express,middlewares Do you think im able to get one?Where can i find a jr job?

Submitted March 29, 2020 at 12:23AM by the_realAlex

I built a website (http://dothyhaveit.com) with which you can check for the inventory of major retailers before your grocery run.

I'm sorry if this is not the right place for it, but I wanted to get the information out. It could be helpful for a lot of people.Hey reddit! Hope y’all are staying safe. I spent the good part of this past week building a website (dothyhaveit.com). It lets you search across major retailers like Walmart, target, etc. and get the inventory for the item you’re looking for. As of now, you’ll be able to search for products in Walmart and Target. The other day, I had to go to a couple of different stores to find a jug milk.  This only increases the risk of you getting exposed significantly, and realized it’d be so much better if I could check for it beforehand. Social distancing is how you flatten the curve. With the website, you could see if it available before you go on your grocery run. Visit that one store instead of many. Please feel free to send me a message if you have a question, suggestion, etc. Disclaimer: With Walmart, the stocks are either not updated in real time, or they just don’t maintain it. I’m not certain at this point. ​The meme section;This is Bill; Bill uses dothyhaveit.com to search for products before he heads out; Bill is smart; Be like bill. 

Submitted March 28, 2020 at 11:57PM by the-ML-noob

How to improve this code flow?

I need sugestion for best code practices on this code:https://pastebin.com/DpUSCwfp

Submitted March 28, 2020 at 11:02PM by patilanz

Mongoose - linking two collections

I am currently designing a system storing information about a users and their payment methods.I have a users and a paymentcard collection. Basically what I want to do is, when I a crate a new payment card record, I want to assign it to a user by including that users mongoID in the payment card document, and then be able to retrieve the user AND all payment cards associated with him by querying the db with the user’s mongoID. How can that be done?

Submitted March 28, 2020 at 07:56PM by Fizaraz

Connect mysql database with node js application on cpanel

What must be considered when launching the server in production mode?

What should we consider when hosting a node.js web server? Can you give me some advices for balacing, relaunching on error, database backup and updates when the server is already online and receives clients. Or any good advice to be prepared for the real world.

Submitted March 28, 2020 at 07:19PM by patilanz

Having trouble opening up node?

Hi all,I’m very new to coding and programming, but I was looking for some help. I used home brew to download the latest version of node on my MacBook. My terminal says it’s installed but not linked, and when I try to link it, it says this:Error: Could not symlink include/node/common.gypi Target /usr/local/include/node/common.gypi already exists. You may want to remove it: rm '/usr/local/include/node/common.gypi'To force the link and overwrite all conflicting files: brew link --overwrite nodeTo list all files that would be deleted: brew link --overwrite --dry-run nodeI’m not sure what this means, or if it’s potentially related to my main issue, which is that node refuses to open: I’ve tried to open it using node -v as I’ve seen on the Internet, but it keeps saying the command isn’t found.

Submitted March 28, 2020 at 05:15PM by blirbo

Best Resources For NodeJS and Project Ideas

I am going to complete Node Js Course by Andrew mead next week and I'm thinking about What should I do next complete another tutorial or Start working on a project.If Project can you please give some ideas?And what do you think I should do to master Node as I want to work as freelancer

Submitted March 28, 2020 at 02:10PM by Bilal009900

How to speed up Node.js modules installation in CI/CD Pipeline as of 2020

https://medium.com/@jeromewus/how-to-speed-up-node-js-modules-installation-in-ci-cd-pipeline-as-of-2020-4865d77c0eb7

Submitted March 28, 2020 at 12:51PM by JeromeWu

how do I uninstall express-generator globally?

I was following the VS code tutorial on debugging and they asked to install express-generator, so I installed it, and my localhost:3000 is always running now without typing any commands. I tried to uninstall it using this command.. but even after that, localhost:3000 is still running.and it's bit annoying tbh. how can i stop this ?​https://preview.redd.it/zsfi6wi4rep41.png?width=1366&format=png&auto=webp&s=12abfa4220113a5d9ae8d7b60219c0775a497e44

Submitted March 28, 2020 at 12:35PM by Sakalalaa

What are some advanced skillsets required from senior node.js developers

I am just posting those I saw the most often:Automated Testing, DevOps - CI/CD Experience with Cloud technologies like AWS, Azure or Google Cloud Knowledge of security and privacy standards, and authentication protocols (e.g. OAuth2, OpenID Connect, SSO, Keycloak integration, ...) Experience with designing and developing distributed systems Experience with Container Technologies Docker - (swarm, compose) Experience with scheduling and orchestration technologies (kubernetes, zookeeper, etcd, consul) Experience in creating API design/technical documentation (Raml, swagger) Experience in using debugging and observability tools for live systems dtrace, strace dtruss Experience in post-mortem analysis of a node process Experience in messaging protocols such as AMQP (, Rabbitmq, Kafka, Nats, Redis). Can you add to this list and post some relevant video tutorials, books and resources for learning them?

Submitted March 28, 2020 at 12:15PM by jasonscript

A Practical Guide to Memory Leaks in Node.js

https://www.arbazsiddiqui.me/a-practical-guide-to-memory-leaks-in-nodejs/

Submitted March 28, 2020 at 11:51AM by paashabhai

retrieve and decode the blob content from database

Hi I am developing a node js API that saves the users records including images. I store the image in database using Buffer.form( ) blob. Now I want to retrieve these images and send back as a response of http request.Before insert to database i convert it to buffer asconst bitmap = fs.readFileSync(file);const buf = new Buffer.from(bitmap);​please guide me to do this.View Poll

Submitted March 28, 2020 at 11:44AM by hammadali598393

What can a i code in nodejs

Hello, I've been in nodejs for 2 months, i now the basics like JWT, Api rest,expreess,mongodb,moongoose and i want to do a personal proyect but i have no ideas of what can i doPlease give me ideasThanks

Submitted March 28, 2020 at 10:08AM by the_realAlex

Friday 27 March 2020

Question about oAuth

Hey guys, I’m trying to make a full stack app right now that utilizes google’s API. It’s MERN stack, and I’m trying to use passport, but i’m confused about how the redirect works. How do I call my express app’s /google route from my react client app, and then get redirected to react client with the token? I’m honestly just kind of flustered right now and would really appreciate an explanation of the flow when there’s a decoupled client app involved! Thank you!!!

Submitted March 28, 2020 at 06:13AM by TheRealSteven

how to properly make a CSS file

I finally caved and decided to make a CSS file I run Linux but I'm not 100% sure how to make a CSS file I'm pretty sure it should go Website ------> css ----->css.js I think im not sure and I need some help and with a css file it would look so much better

Submitted March 28, 2020 at 04:02AM by Juls0730

Problem testing a promise in a setInterval() with Mocha and Sinon

Hello, I'm having trouble for testing a property in a class which is regularly updated after requesting my database. My class looks like this:class Color { private _green: string = '' private async update() { const greenColor = await API.getGreenColor() this._green = greenColor } private regularUpdate() { setInterval(async() => { await this.update() }, 10000) } public async start() { await this.update() this.regularUpdate() } public get green() { return this._green } } What I've done to test 'start()' and it works:describe('start()', () => { it(`Should set the color`, async() => { sinon.stub(API, 'getGreenColor').resolves('green') const color = new Color() await color.start() expect(color.green).to.eql('green') }) }) Now what I'm doing to test the regular update and it fails:describe('regularUpdate()', () => { it(`Should regularly update the color`, async() => { const clock = sinon.useFakeTimers() const stub = sinon.stub(API, 'getGreenColor') stub.onCall(0).resolves('green') stub.onCall(1).resolves('darkGreen') const color = new Color() await color.start() expect(stub.calledOnce).to.be.true // <-- Passes expect(color.green).to.eql('green') // <-- Passes clock.tick(15000) console.log(color.green) // 'green' expect(stub.calledTwice).to.be.true // <-- Passes expect(color.green).to.eql('darkGreen') // <-- FAILS }) }) So the second call is called with the wrong data? Does anyone know why? I specify that if I use console.log to test "manually", the regular update works.

Submitted March 27, 2020 at 11:36PM by GreenMonkeyBoy

encountering issue when attempting to run 2 node servers within a single node project?

I've created a new node project in VS Code.I created a single node server file (server.js) in the project and was able to run it by configuring a new child property in the package.json scripts config section.I created a second node server file (authServer.js) in the project and configured an additional child property in the package.json scripts config section.The first node server runs successfully when I npm run its package.json script.The second node server fails when I npm run its package.json script with error "Cannot find module .\index.js."An index.js file was not included in the new project by default. I'm following a demo vid on YouTube which also does not have an index.js file at the root but the YouTube vid example loads up the second server without issueSo it looks like an index.js file or some special config is required when 2 node servers are loaded from the same project.Any idea what I might be missing here or how to fix? Like I mentioned, the example YouTube vid ran the second server from the project without issue without having an index.js file in the project so I'm not sure why my local project is throwing an error?

Submitted March 27, 2020 at 11:52PM by random503

Where can I learn node.js

Hello, I’ve been studying js for a while now and I think I’m ready to learn Nodejs, I’ve been using treehouse to learn but it seems like it’s content on Nodejs is not very detailed.So I’m looking for a affordable place to learn node.

Submitted March 27, 2020 at 11:23PM by JS-error

How do I deploy to heroku from github if essential files are .gitignored?

Is there a workaround here? Im used to using heroku for small projects but now I'm trying to deploy something with .gitignore from a github repo and obviously it won't work because the files aren't actually being uploaded to github.

Submitted March 27, 2020 at 10:27PM by TelepathicDorito

Making a recipe book - how do I implement the recipes to the corresponding user?

Like, I have my user controller, routes, database query, but how would I implement the user made recipes to store them? I’m guessing to create a second database query just for recipes but still don’t know how to go about that. Any advice?Sorry if any terminology is off, first project I’m making after learning Node :)

Submitted March 27, 2020 at 08:18PM by flat_soda_club

Where is node_string.cc used in node.js

I was browsing through node.js source code from Github and I came accross node_string.cc and node_string.h files. Does anyone know where they are used in node.js ?

Submitted March 27, 2020 at 06:58PM by sanjay_i

bcrypt.compare() lets every password through

I am making a user authentication system. Registering users and hashing password works, however when I try to log in with the correct username, my isValidPassword always lets me log in with whichever password. Do you see any errors/solutions to this?I need to use .pre() because I have a route to update user details, and without it the changed password is saved as plain text and not hashed.​const mongoose = require('mongoose') const bcrypt = require('bcrypt'), SALT_WORK_FACTOR = 10; const Schema = mongoose.Schema // Schema for making a new user account (for employees) const User = new Schema({ name: { type: String, required: true }, surname: { type: String, required: true }, role: { type: String, enum: ['Admin', 'Manager', 'Advisor'], required: true }, username: { type: String, unique: true, required: true }, password: { type: String, required: true } }) // Generates salts and hash-encrypts the password before writing it to the database User.pre('save', async function(next){ const user = this; const hash = await bcrypt.hash(this.password, 10); this.password = hash; next(); }); User.methods.isValidPassword = async function(password){ const user = this; const compare = await bcrypt.compare(password, user.password); return compare; } module.exports = mongoose.model('User', User )

Submitted March 27, 2020 at 05:04PM by Fizaraz

GraphQL Mesh - access services using different API spec with GraphQL queries

https://blog.graphqleditor.com/the-graphql-mesh/

Submitted March 27, 2020 at 04:09PM by oczekkk

Is using ts-node to run a Express/TypesScript server in production a good idea?

Hi guys!At the moment Im working on writting server using TypeScript/Express and Im in the step of publishing it.I wanted to dockerize this project and run it inside a container in production.Is okay to use ts-node to keep my server alive or is not recommended?Any recommendation, hint is welcome!Thanks!

Submitted March 27, 2020 at 04:17PM by mrtebi

Module.exports tips/ best practices

Hi folks,I am using NodeJS in tandem with express for my server and I have hit a problem.I am using module.exports as my methods, and I am trying to pass the ID from the client to the server to delete a specific document.The ID is being sent successfully, but I am struggling to pull that ID and pass it through the function.Route for the delete function (Server)router.delete('/RemoveDealDetails/:id', DealDet.RemoveDealDetails);Delete Function (Server)module.exports.RemoveDealDetails = router.delete('/:id', (req,res) => {DealDetails.findByIdAndRemove({_id:req.body.id}, (err,doc) => {if (!err) {console.log("RemoveDealDetails: " + doc);res.send(doc);} else {console.log("Error in DealDetails save, Find By ID and Remove : " + JSON.stringify(err, undefined, 2));}});RemoveDealDetails method (Client)console.log("Remove Details: " + _id);return this.http.delete(environment.apiBaseUrl + "/RemoveDealDetails" + \/${_id}\);``I am passing the ID through the URL.

Submitted March 27, 2020 at 02:16PM by wazzalk

Learn how to build and deploy a serverless API using NestJS (online workshop)

https://nitro-stack.github.io/nitro-workshop/

Submitted March 27, 2020 at 01:01PM by sinedied

SocketIO server works fine on Heroku but on Amazon Beanstalk it randomly receives duplicate messages. Why?

I want to move my SocketIO app to Amazon because Heroku randomly restarts it and this is not tolerable.It works, except it receives duplicate messages randomly from the client. Which I assume means the server is sometimes failing to confirm to the client that a message was received, so the client is sending it again.I know this is happening by looking at the logs.It also randomly sends an incomplete portion of a message (or at least, the server receives an incomplete portion of it.Does anyone have any idea where I should begin looking to solve this? How does SocketIO "know" that the environment is different when it's hosted on Amazon to cause this bug?The client is SocketIO-client running on Node, by the way.

Submitted March 27, 2020 at 12:47PM by MelerEcckmanLawler

Best way to store API keys manually for a self hosted API?

/r/learnprogramming/comments/fpusy5/best_way_to_store_api_keys_manually_for_a_self/

Submitted March 27, 2020 at 11:26AM by amitgoren

Puppeteer or: How I Learned to Stop Worrying and Love the Automation

https://medium.com/@ali.bahrami/puppeteer-or-how-i-learned-to-stop-worrying-and-love-the-automation-92e96f4901e7?source=friends_link&sk=fc259197443e7f702fe91557c91a07ae

Submitted March 27, 2020 at 10:53AM by 0x414c49

Full automation of release to NPM and Docker Hub with GitHub Actions and Conventional Commits

https://www.asyncapi.com/blog/automated-releases/

Submitted March 27, 2020 at 07:51AM by r-wabbit

Sync data between two rest APi's

Hi All,After learning vanilla javascript im learning node.js as we speak.The number one reason i want to use node is to connect two platforms REST API'sSo for example, i have an ecommerce platform that receives orders. and i want to send the order information to and email platform so that i can send some e-mails about their order.Is it possible to sync this directly. or is a database necessary.Can someone point me in the right direction? are there good articles about this? or tutorials, or modules.​Thanks

Submitted March 27, 2020 at 07:53AM by Bernardusa

Express and Nginx figthing over routing ?

So i have a strange configuration that i need until i get to refactor a project later this year.it is a static index.html landing page served with a location root "/" by NGINX.i have a slash location:​```location /channel/ { proxy_pass http://node_server_channel:5000/; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_set_header X-Ssl on; proxy_cache_bypass $http_upgrade; } ```that express.js then handles. Express just serves a static folder with auto-generated content that a user can then navigate around in.It works well in the sense that any appending slashes like:/channel/open/but ONLY if i have a trailing slash after "open". If i leave it out then NGINX will throw a "404 Not Found", if i keep it in, it works as intended.The thing is that a user should be able to click on a folder in the static served directory to traverse a file structure, and the way that works in a browser is that it does not append a trailing slash to a directory name when clicked, so NGINX then throws the "404".I have tried a NPM package called 'express-slash' but that did not solve the issue.i was hoping someone here had some suggestions on what i could try out next?

Submitted March 27, 2020 at 07:53AM by 5t4iN

Thursday 26 March 2020

Node v13.12.0 (Current)

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

Submitted March 26, 2020 at 11:17PM by dwaxe

Help with a quick issue. Making an http request from one express server to another but the request keeps getting refused. Anyone know why this might happen?

As I said in the title, I just have one server making a request to another server to get some information. It's not a cors issue because I'm accepting all request in my dev environment, plus the front end server can make requests to it just fine, as can I from the node repl using the same code. This is probably the first issue I've had where I'm at a complete loss about why it's happening. I'm using axios to make the request and all I get back is this:Error: connect ECONNREFUSED 127.0.0.1:9000 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1113:14) Desperate for help with this, it's been driving me crazy.

Submitted March 26, 2020 at 08:02PM by NotReallyASnake

Create a nodejs function to take parameters and post them to a url like form-data

I am trying to create a NodeJs SDK for my hosted payment gateway. So I want to create a function that takes the necessary parameters and then POST it to the gateway's URL based on the environment. I have almost completed everything but the problem is I can't figure out how to redirect the req such that it also POST's the parameters and what to return in that case.My basic question is that if we handle a request and my method is being used then what should I return in my method definition and what should I write after my req.const mylib = require('mylib'); app.get('/', (req,res)=>{ mylib.createTransaction(txnId, amount, firstName redirectUrl, hash,function(error, response, context) { //what should I write here or in my method definition to redirect this req to a URL and end not await for res. }); });

Submitted March 26, 2020 at 08:04PM by umernaeem217

Looking for feedback for node with javascript lawn mower assignment

Hi,​I got previously assignment to design lawn mower.​After I submitted it I got this feedback:Incorrect handling of input, needed to add .trim()Incorrect error handlingIncorrect Split for classesToo many useless variables​And then the assignment got rejected.​Link for the assignment and my solution: https://github.com/saifabusaleh/lawn-mower​I would be grateful if you can give me more details feedback about my mistakes.I have experience only with TS & Angular in Front-End, and knowing my mistakes will help me forward.Thanks

Submitted March 26, 2020 at 08:13PM by ExectAsync

Build a Node.js Tool to Record and Compare Google Lighthouse Reports

https://css-tricks.com/build-a-node-js-tool-to-record-and-compare-google-lighthouse-reports/

Submitted March 26, 2020 at 07:35PM by dobkin-1970

Most end-points returning a 404

I'm making my call both from localhost:2018/ and from an api located at localhost:8080/new. Only request working is POST on /authconst express = require("express"); const app = express(); const port = 2018; //Port used // Mock data imports //One data import from post is missing here const renewalResponseJSON = require("./data/renewalResponse"); app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from res.header( "Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept" ); next(); }); app.get("/entity/:uid/canRenew", (req, res) => { const uid = req.params.uid; if (uid != null) { res.status(200).send(renewalResponseJSON); } else { res.status(500).send(); } }); app.post("/auth", (req, res) => { res.status(200).send(principalJSON); }); app.get("/entity/plate/:plate", (req, res) => { const plate = req.params.plate; if (plate != null) { res.status(200).send(fileJSON); return; } else { res.status(500).send(); return; } }); // Run server app.listen(port, () => console.log(`Mock-server listening on port ${port}!`));

Submitted March 26, 2020 at 06:52PM by mslayaaa

I can code some Node. What's next ?

Hello everyone!I've been into NodeJS for about a year(maybe a bit more), and I already feel kind of confident in using it, and if I face a problem, I'll probably find a way to solve it. BUT I do have a strange feeling of missing something essential for a backend developer.There a list of things I can do in a moment - RESTful API, Auth, mongodb, deploying to Amazon EC2Could some of more experienced developers help me out with that? All I do is simply creating one route by another, looking for data insides of a DB, and returning a response. I strongly believe that does not make me a Junior Backend Node developer at all.​What should I read/learn to to become a better developer?

Submitted March 26, 2020 at 06:16PM by y4mat0

Code/state sharing between NodeJS and client?

anyone familiar with bcrypt here ?

hello fellas;https://preview.redd.it/cmu4l1tti1p41.png?width=1366&format=png&auto=webp&s=e609ef1cc47e00baf20234846c90985581d83e5cI'm trying to make a signup API and using bcrypt.hash to encrypt my password.however, I am not able to save the new user. I tried to debug the code and send res.json with some dummy data before user.save() and I'm getting back the dummy data.so apparently the bug is in the .save() function as it's always reached the .catch() function and displaying the error.. is there anything wrong with my code?although I literally used the same syntax to other data

Submitted March 26, 2020 at 04:07PM by Sakalalaa

Want to learn back end

Hello,I know there are many resources out there and have looked at the wiki/other guides, but I have some more specific preferences/situation that I'm hoping you guys can help me out with.I have zero experience in web dev or programming and I'm trying to build a (mechanically very simple) multiplayer game with not more than 10 players. I've been learning HTML/CSS/JS for two weeks and have some ability to write algorithms, as well as have set up very basic interactive web pages, but no knowledge of back end or how to handle the data, send and receive it via web sockets or anything. Whenever I search up 'learn back end' or 'learn node/express' all the top answers say to just start writing code - I would love to do this and already have my project in mind, the reason I'm learning all of this, but I physically don't know how to begin. Lots of resources assume prior knowledge of web dev principles/other back end languages and frameworks, which I don't have.I can't learn from videos at all, which is a major reason why I'm asking here. I learn best from written resources. Can anyone recommend written resources for absolute beginners on back end, taught using Node/Express?Thanks for your help.

Submitted March 26, 2020 at 03:47PM by NotHarryEnten

Help with parsing CSV to ICS

I come to you in dire need. I've been trying to parse the csv file to ics for a few days now and got really stuck at one point, It parses it alright but at the end of the file in ics it displays only the last one. So i need "element" to repeat as far as the csv rows go and parse into one event.ics. What am i doing wrong?const { writeFileSync } = require('fs') const ics = require('ics') const fs = require('fs') const fastCsv = require('fast-csv') const csv = ('csv/example.csv') const moment = require('moment') fs.createReadStream(csv) .pipe(fastCsv.parse({ headers: false })) .on('data', (row) => { const [Anrufsart, Datum, Dauer, Nummer, Kontakt] = row let singleDatum = moment(Datum).format('YYYY'); let singleMonth = moment(Datum).format('M'); let singleDay = moment(Datum).format('D'); let hours = moment(Datum).format('HH'); let mins = moment(Datum).format('mm'); const icsArray = []; for (let i = 0; i < row.length; i++) { const element = { summary:Anrufsart, title: Kontakt, start: [parseInt(singleDatum), parseInt(singleMonth), parseInt(singleDay), parseInt(hours), parseInt(mins)], duration: { minutes: parseInt(Dauer)}, description:Nummer } icsArray.push(element) } const { error, value } = ics.createEvents(icsArray) if (error) { console.log(error) return } setTimeout(() => { writeFileSync(`${__dirname}/event.ics`, value) }, 2000); })

Submitted March 26, 2020 at 01:44PM by markoza94

I was recommended SuperTokens for Auth in Reddit comment section, So happy!

As a Junior Dev, Auth is hard. I couldn't find much online explaining how to have a secure authentication system for my app other than the quick-start JWT guides or Auth0. At one point having 30+ tabs to try and understand this shiz. Long story short Auth0 ≠ Oauth. Heh. So after talking on Reddit, I was recommended a product (It's open source) here in the comment section.I found SuperTokens! it took me 1 day to implement and can now peacefully delete all my tabs. And I am loving it! It uses Cookies that contain an access token which expire and must be refreshed with a refresh token. It can detect intrusions and provides more protection than I could have if I'd done it myself. Didn't bother trying it until looking online for a month and giving up.https://preview.redd.it/q1rwrmdx80p41.png?width=1682&format=png&auto=webp&s=46b2269011225a4d563f7265514def8f54a81561Had to post here to show gratitude as one of their team screenshared to answer some of my questions on how it works. And this is what I've understood:How it works:Using a stack of your choice (currently Node + MySql/Postgres) you find in the docs that you need the CLI, to start the process daemon, an Init() function in your app providing the port for the Auth service and then must create the necessary DB and tables. DB for example called auth_db, with 3 tables, key_value, which has the rotating signing access key (for access token) this is automatically generated and rotated. The past_tokens table and a sessions table that contains all user sessions currently logged in.To implement in your code, you call createSession(...args) at /login, this returns a Response with headers that contains all of the cookie/token information. Next you'll have middleware (if using express) that checks the cookies on every api request. And if this fails you have a /refreshSession (or whatever) endpoint for creating a new session for a user that's already logged in. So first Login (/login), then Middleware, then Refresh (/refreshSession).The docs explain how to log users out, destroying their sessions and error handling for detecting breaches And all of this info has useful examples.​It all works smoothly and one thing I didn't really understand but now do and want to share just incase is that: all of this is tested in insomnia/postman via passing correct headers and cookies with each request. But all of the cookie management and header management is handled on the front-end automatically via the front-end SDK they've built (ios/android/web).My opinion is that this is a great solution in comparison to the lock-in options like Firebase, Auth0. Which have benefits in their own ways but this takes the cake for me. With very-little set up. Smooth transition between free (community + opensource) and pro (paid but less than $300 a year). And some really nice security features. Blacklisting, session revoking, refresh & rotate, anti-CSRF. Anti XSS.I'm using this because I reason that it is a dedicated solution and probably better than what I can create myself. Easy to set up and I've never seen something that I actually trusted a little.So here's the Docs,Cheers

Submitted March 26, 2020 at 12:07PM by Anasurimbor_Cale

Node.js Modules: Learn how to Import and use Functions from Another File

https://www.stanleyulili.com/node/node-modules-learn-how-to-import-and-use-functions-from-another-file/

Submitted March 26, 2020 at 11:34AM by Stanulilic

Prototype pollution vulnerability in minimist npm package

https://snyk.io/blog/prototype-pollution-minimist/

Submitted March 26, 2020 at 11:39AM by lirantal

How does Knex know that the function is the last function in the chain

Hi, I was wondering how knex runs it's queries ?to query user data I can write my query in two ways: await knex.from("users").select("id", "label") await knex.select("id", "label").from("users") and both give me same results. I was wondering how knex know that it is the last function and runs the query against the database.I only know the way to add a execution function, something like this:await db.select("id", "label").from("users").run()``` let sql = { select: [], from: [], where: [], group: [], having: [], order: [], LIMIT: false }export default { select(...args) { sql.select.push(args) return this }, from(...args) { sql.from.push(args) return this }, run() { let query = ""query += " SELECT " + sql.select query += " FROM " + sql.from console.log(query) } } ```Can anyone explain this to me ? Thx!

Submitted March 26, 2020 at 10:02AM by style-112

convert unicode text to bitmap

hello guys, I'm using jimp plugin to manipulate images.I'd like to write text to a bitmap , but jimp only supports bitmap fonts.so it is not possible to convert every chinese or tamil etc.. characters to bitmap.does anyone know of a good workaround ?if I can get bitmap, I can draw it on an existing jimp image object.any help is greatly appreciatedPS : using nodejs in azure functions

Submitted March 26, 2020 at 09:25AM by zzzxtreme

How do you structure your tests in a suite?

https://i.redd.it/5sh4ajub8zo41.png

Submitted March 26, 2020 at 08:21AM by yonatannn

How to detect which node module(built in too) used in a Node aren't supported in browsers?

I have a node app which uses some of the core node modules and other node modules, is there any tool/method to detect them so I can find polyfills and replace those modules?

Submitted March 26, 2020 at 06:42AM by rathod-sahaab

(Solved) How to access webserver via wifi

when I try to use my webserver over the wifi I use my phone because data and when I try everything like my external IP my local IP works on my computer that I'm hosting the webserver 172.16.0.XX and when I use my external IP 174.126.XX.XXX im running on Linux im running on port 8080 and im using ngrok to forward please helpwell I found the problem if any of you are having the problem use ngrok http the port and dont use anything after it just take the forwarding http and put it into your browser

Submitted March 26, 2020 at 07:16AM by Juls0730

Wednesday 25 March 2020

Need help with map website with node backend

IDK if this is the place for my request but here I go.​I have a small university project where we need to develop a mapping website similar to mask.goodideas-studio.com but for Hong Kong, instead of Taiwan. This website is based on data from the government but our version is crowdsourced. The API for it has already been developed but we need developers who can help implement it.​Honesty time: there is no pay but it is for a good cause imo.​Reply or PM if you're interested in helping or maybe guide me to someone who you think can help.​Thanks.

Submitted March 26, 2020 at 05:52AM by AaditO

Nodejs interview on podcast

I’m looking for someone that is very knowledgeable on Node.js to be on my podcast for a 30 minute conversation about node for beginners. If interested please email me. Marcelo@themarcelolewin.comb

Submitted March 26, 2020 at 03:05AM by themarcelolewin

What does post-mortem analysis of a node process mean and how do you learn to do that?

Saw that in a job posting and I was wondering how you could learn doing that.

Submitted March 26, 2020 at 12:41AM by jasonscript

[Question] In a signup endpoint with Mongoose, should I validate the e-mail address by RegExp in the Schema or with "if statement" in the Route or both?

as the title.please explain your answer if you can so I can understand why

Submitted March 25, 2020 at 11:13PM by AhmedHossam01

Collection of objects from response

I am trying to create a collection of objects from an axios get, but I'm not sure how to convert my json response data into the collection and what the best practices would be.Here is my code:class TimeSeries {constructor(Confirmed, CountryRegion, Date, Deaths, Lat, Long, ProvinceState, Recovered)  {this.Confirmed = Confirmed;this.CountryRegion = CountryRegion;this.Date = Date;this.Deaths = Deaths; this.Lat = Lat; this.Long = Long; this.ProvinceState =  ProvinceState;this.Recovered = Recovered;this.ActiveCases = confirmed - recovered - deaths;  }}This is where I get my data, but I don't know how to get the json into the class and also create a collection:async function getTimeSeries() {try {axios.responseType = 'json';const response = await axios.get( 'https://pkgstore.datahub.io/core/covid-19/time-series-19-covid-combined_json/data/845fcaa5cc5dac944cf798f2bc96c46f/time-series-19-covid-combined_json.json')    .then(function (response) {console.log(response.data);response.data      .forEach(({'Country/Region': CountryRegion, Date, Confirmed, Recovered, Deaths }) =>console.log(\${CountryRegion} : ${Date} active cases: ${Confirmed - Recovered - Deaths}`))     });`Any help is appreciated!

Submitted March 25, 2020 at 11:48PM by hololensful

slash in data json label

I am trying to get to the country region data label here:Snapshot of jsonusing this code here:async function getTimeSeries() {try {axios.responseType = 'json';const response = await axios.get( 'https://pkgstore.datahub.io/core/covid-19/time-series-19-covid-combined_json/data/845fcaa5cc5dac944cf798f2bc96c46f/time-series-19-covid-combined_json.json')    .then(function (response) {console.log(response.data);console.log(response.status);console.log(response.statusText);console.log(response.headers);console.log(response.config);response.data      .forEach(({ Date, Confirmed, Recovered, Deaths }) =>console.log(\**$(Country/Region)** : ${Date} active cases: ${Confirmed - Recovered - Deaths}`))     });`And my console looks like this:$(Country/Region) : 2020-03-05 active cases: 0I have tried putting Country/Region in quotes, and even removed the slash but now luck. Any ideas?

Submitted March 25, 2020 at 09:58PM by hololensful

Backpressure problem in http.ServerResponse

Hi guys, I'm new to Node so I'm practicing some backend development using only pure Node (no frameworks) to get a feel for it, and I thought I'd give streams a try to process a somewhat large text file (a 200 MB .txt file).I think I have a backpressure problem in my code and I'm not sure how to solve it. Here's the code:// The default chunk size of Streams created by createReadStream is 64kb, which // is far too small for big files. This CHUNKSIZE is set to 1 MB const CHUNKSIZE = 1048576; const server = http.createServer((req, res) => { if(req.url == "/") { // The following hack doesn't seem to work //res.socket._writableState.highWaterMark = CHUNKSIZE; const stream = fs.createReadStream(__dirname + FILENAME, {highWaterMark: CHUNKSIZE}); // outputs "16384", as expected. If I uncomment the hack above, it does // show CHUNKSIZE, but still doesn't seem to work console.log("res.writableHighWaterMark: " + res.writableHighWaterMark); let fileChunkNum = 1; stream.on("data", (chunk) => { console.log("\nFile stream received chunk #" + fileChunkNum++); console.log("Megabytes read so far: " + (stream.bytesRead / 1024 / 1024) + " MB"); }); // FIXME: I guess this is taking forever because of res' default highWaterMark (16kb) stream.pipe(res); } else { res.end("Request not handled"); } }); Now, I've been reading about Streams and the problem here seems to be that there's no way to set the highWaterMark of an already created Stream (in this case, the http.ServerResponse that createServer passes as the second argument to my callback). I've tried to hack around it by manually setting the highWaterMark of the ServerResponse's socket's _writableState but that doesn't seem to work (even though the correct value is displayed when I console.log it). If I remove the call to stream.pipe, the chunks are very quickly logged in the console, so I guess what's happening is that res' paltry 16kb buffer is getting overwhelmed. Is there a solution I am not seeing? Is my whole approach just completely wrong? I'm open to any suggestions.

Submitted March 25, 2020 at 08:15PM by El_bigote_de_Dali

Using node for server-side machine learning

So, I am planning on a client uploading some data to the server and the server doing some machine learning regression and returning the result to the user.I heard Node.js is not very efficient at doing such things due to it's single-threaded nature.Is it possible to do this machine learning on the server end with potentially hundreds of clients? Or, will another server side language like PHP or Python's libraries be a better choice?

Submitted March 25, 2020 at 06:44PM by SuperSaiyan1010

Difficulty in getting Jest to recognise a thrown error

[Noob Here]Trying to use nanoid on AWS Lambda, some help?

Hey guys!I'm trying to use nanoid in aws lambda without success, because it warns that the variable is not a function:const nanoid = require('nanoid'); const AWS = require("aws-sdk") exports.handler = async (event) => { var i = 10; while (i--) { console.log(nanoid()); } }; the error:Response: { "errorType": "TypeError", "errorMessage": "nanoid is not a function", "trace": [ "TypeError: nanoid is not a function", " at Runtime.exports.handler (/var/task/index.js:7:21)", " at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)" ] } and what im follow:https://www.npmjs.com/package/nanoid

Submitted March 25, 2020 at 06:03PM by LuizThiago

Integrating TypeScript with GraphQL

https://blog.logrocket.com/integrating-typescript-graphql/

Submitted March 25, 2020 at 04:37PM by alexander-nnakwue

4 possible reasons why your Docker containers can’t talk to each other

When you put a NodeJS application in a container, something that often breaks is the connection to the database and other services. If you're struggling to get two containers to talk to each other, you can try these 4 troubleshooting steps to quickly fix your issue. In short:Containers should be in the same networkConnecting to a container by its name isn't possible in the default network, create on of your own insteadMake sure you are using the correct IP addressThe network should have ICC enabled (it does by default)In the article, I elaborate a little bit more on each bullet point and show you a solution. This isn't a comprehensive list, but hopefully it helps some folks who have already spent several hours debugging their issues.

Submitted March 25, 2020 at 04:40PM by _maximization

Any alternatives to the Johnny-Five Inventor's Kit?

I'm a fulltime JS developer and am interested in trying my hand at hardware instead of just software. I've been looking at the J5 kit but it seems like their ecosystem for alternatives devices (cameras, USB devices, audio, etc.) is rather lacking compared to other systems I've seen.Am I just missing something obvious that makes the ecosystem larger than it seems? Or is there an alternative kit I should be looking at to get started?

Submitted March 25, 2020 at 05:07PM by AshenLordOfCinder

Good passport manual?

Hi,​so I'm going crazy with PassportJS... I read their docs several times and I just don't get it. Does anyone have a manual that actually first talks about the idea that's implemented? I do know the process of authenticating a user, I could write my own. I don't get their "workflow" though.​I'm currently reading their source code since I wasn't able to find a proper manual. Anyone knows a good ressource? :) Would be awesome. Thanks

Submitted March 25, 2020 at 04:19PM by leaiaiai

Flutter Client subscription to nodejs/nestjs server

Hello guys,I have a flutter application where I use web_socket_channel for a chat function in the app.In the flutter application I implemented a SubscribeRequest with:{"command":"subscribe","identifier":"{\"channel\":\"ChatroomChannel\"}"}​How can I subscribe in a node/nest server to that channel?​Thank you!!

Submitted March 25, 2020 at 02:44PM by faux190

Playercast - node app for casting to media player and controlling playback remotely.

https://github.com/Rafostar/playercast

Submitted March 25, 2020 at 02:15PM by Rafostar

Creating web app using node js

https://www.bloggerdrive.com/nodejs-tutorials-creating-a-simple-web-app/

Submitted March 25, 2020 at 12:28PM by hatim112

ElectronCGI 1.0 - Cross Platoform GUIs with Node.js and .NET Core

https://www.blinkingcaret.com/2020/03/25/electroncgi-1-0-cross-platform-guis-for-net-core/

Submitted March 25, 2020 at 12:16PM by ruidfigueiredo

Authentication for API Routes using JWT and bcrypt (Theory + Code)

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

Submitted March 25, 2020 at 11:49AM by bmvantunes

Node.js for ecommerce?

Hello everyone!I am thinking about using nodejs to develop an ecommerce site. It's nothing big: maybe 50 products maximum and no special features. I've found a lot of posts claiming that nodejs is unfit for ecommerce because it's not mature enough yet or it is not fit to use together with relational databases, etc. So what do you think? Is there a lack of ecommerce tools/plugins to build a complete functional and secure ecommerce site? And is there really an issue using nodejs together with relational databases? In general, Is nodejs a less appropriate alternative for ecommerce than let's say Django or Wocommerce? If that's the case, then why?All thoughts and ideas are highly appreciated!

Submitted March 25, 2020 at 10:04AM by DevLopp

Problem debugging Node.js application in WebStorm

Hello,I'm completely new to Node.js, coming over from c++. I'm trying to make a module for an existing node.js application. Essentially I'm just writing a function to parse a text file with a specific format. I can't set up the parent application in Webstorm so I tried just make a simple html file to call a script, which then calls my module. However, while my script seems to be launched, my module doesn't get called. My code looks as follows:E:\Productivity\WebStorm 2019.3.4\Projects\mysettingsparser\Caller.html Title E:\Productivity\WebStorm 2019.3.4\Projects\mysettingsparser\index.jslet patcherPath = "S:\\ParentScript\\Modules\\MyModule"; let settingsLoader = require('E:\\Productivity\\WebStorm 2019.3.4\\Projects\\mysettingsparser\\settingsLoader.js'); function go() { document.write("hello!"); document.write(settingsLoader.testfunction()); settingsLoader.loadPackSettings(patcherPath); } E:\Productivity\WebStorm 2019.3.4\Projects\mysettingsparser\settingsLoader.jsmodule.exports = { testfunction: function() { return "Testing!"; }, loadPackSettings: function(patcherPath) { document.write("Loading!"); let fs = require('fs'); let resourcePath = patcherPath + '\\ResourcePackSettings\\'; // path to resource pack files // look in path and pull candidate files let returnstring = ""; let files = fs.readdirSync(resourcePath); let groupAndFileNames = []; // names of groups in text file for (i = 0; i < files.length; i++) { groupAndFileNames = validatePackSettings(resourcePath, files[i]); for (j = 0; j < groupAndFileNames.length; j++) // go through each group name { returnstring += groupAndFileNames[j][0] + " (" + groupAndFileNames[j][1] + ")"; } } return returnstring; } }; //ValidatePackSettings is defined here but irrelevant (I think) to my problem When I open the html in WebStorm, launch it through Internet Explorer, and click "Start loader", I get the message "hello!" displayed, but then nothing happens (it doesn't call testfunction() and display "Testing!"). I tried setting breakpoints at every line in index.js but when I click debug in Webstorm, it breaks at let PatcherPath, then let settingsLoader, and then it skips all the way to the closing } of the go() function. I think that the overall syntax is correct because WebStorm's autocomplete function recognizes both testfunction() and loadPackSettings(patcherPath) when I call them from index.js.It seems to me that I'm misconfiguring something - the debugger isn't listening to the html file, and then for some reason it skips over my go function even though the first part of go() works because I get "hello!" on my html page.​If someone could give me a hint, I'd really appreciate it!

Submitted March 25, 2020 at 07:01AM by Piranha91

How to validate your request parameters easily using middleware in node.js

https://ranvir.xyz/blog/how-to-write-a-request-parameter-validation-middleware-in-node.js/

Submitted March 25, 2020 at 07:33AM by rangerranvir

Tuesday 24 March 2020

Why bulk email verification/validation services are expensive?

1- Is the technology behind email validation complex? Is there open source email validation script that I can use with some support of some friends who are good at coding?2- Why is it expensive to do email verification/validation? 100k emails validation will cost $200 to $400 ( there are a few services offer it for a bit cheaper but they look crappy. I could have a dedicated server for. $200 from Bluehost for the whole month, does it really put. a lot of bandwidth on server and they why it's expensive?

Submitted March 25, 2020 at 06:38AM by Jack199099

need help sqlite3 module

Hello guys im sure this question has been ask somewhere already but i couldn't find it, i have search the internet for days to the point that im thinking about giving up nodejs (don't get me wrong i like node but it is just frustrating not knowing what to do).My problem is getting data from database in a file.js i have:const sqlite3 = require('sqlite3')const db = sqlite3.Database('pathToDB', (err) => {//connection successful})​const getUser = (username) => {db.get('select from table where username = $username', {$username: username}, (err, result) => {if (err) return err.messageconsole.log(result) //it logs the result ok but it wont return result to the function calling getUserreturn result})​and im calling get user from another file containing a endpoint using expressendpoint { //expressjs endpointconsole.log(getUser('username')) //returns undefined}if somebody can please help me make it that when i call getUser it returns result please thanks im just starting to learn node btw

Submitted March 25, 2020 at 05:01AM by el-calde

Can you add an overlay menu using Express?

I'm currently taking Colt Steele's web dev bootcamp. I've been coding along with it, but I didn't want a carbon copy of what he's done, so I learned a lot more about CSS and DOM manipulation on the side to keep things interesting. I know how to do an overlay menu normally. I have one started on the landing page already. But now I'm trying to implement it into authentication. I'm just learning authentication now, and am using Passport as an extension. What I'm trying to do is make it so that a user can only make a post if they log in. I know how to set it up where it just redirects you to the login page and once you log in it works fine. but what i want is for a menu to come up when you click the button that says you need to be logged in to comment and it gives you the option to login, sign up, and exit. the thing is, i don't know how to do that where it only does that when you're not logged in. once logged in I want to be able to click the submit button and be redirected to the comment posting page, but currently the menu just pops up every time, and when i try other changes, then the menu doesn't pop up and it just goes straight to the post page. not sure if this is totally clear so i have the snippet of code im trying to fix.function isLoggedIn(req, res, next) {if (req.isAuthenticated()) {return next();  }res.redirect('/login');}​so instead of redirecting to the login page, i want it to bring up the menu where i can click login and be taken there. i know it's not necessary, but i'm trying to make things more creative and by doing this im ultimately learning more than just coding along and not making changes. thanks in advance. sorry for not being articulate enough, i'm new to this so trying to explain it isn't the easiest, especially since i don't always know what i'm doing...

Submitted March 25, 2020 at 02:30AM by zolavt

Just finished a Node course. Need help.

Hi peopleI have just finished a node course and yes I learned a lot. However it was a lot of information and it is normal to feel a bit overwhelmed straight after finishing a course. Please allow me to ask a few questions that I have:I learned a lot about authentication. My question is simple, how does backend auth relate to frontend auth? They both have auth aspects, I always thought auth was done in backend, but these days I see auth being done in frontend, how exactly do they relate?Perhaps a weird question, but would someone be able to summarize only the most absolute fundamentals to creating a backend app? For React, for example I already know that, which is to create-react-app, etc. But with backend, you start with npm init, then creating a src folder, index.js folder, that is it, correct?Connected to question 2, database. This makes things confusing also, the course that I learned form used a ton of tools which makes everything confusing - from robo 3t, to downloading mongodb, to using mongoose, to using mongodb atlas, to using mongodb compass. Wow this is all so confusing.TL DR: Basically, could someone please answer question 1, and summarize in the most basic, fundamental way, the steps needed to start and deploy a backend.Thank you all!

Submitted March 25, 2020 at 01:33AM by 5ecured

What is the easiest way to loop through a Sqlite3 database table and create an element for every row?

I am now creating a JavaScript file for my static html page, which sends a XMLHttpRequest to a certain address which is declared by a router in yet another JavaScript file with NodeJS Express Routers. However, (especially compared to the PHP way), this seems really cumbersome to me.

Submitted March 25, 2020 at 01:18AM by KnownToiletBystander

Time Complexity & Big O Notation PT. 2 | Full Examples

https://youtu.be/FAoxU7sXyvE

Submitted March 24, 2020 at 10:28PM by SynthesizeMeSun

Intro to Vue 3.0 Live Stream Tonight!

Hey everyone!A friend and I started started WebOfficeHours to help everyone build for the web - the gist is to basically develop web apps from scratch using the latest tech frameworks or build web apps from existing services at a very low cost.In about an hour, we are presenting Vue 3.0 - please register here to join the streamIf interested in joining this stream or other future streams, make sure to subscribe on our website below.www.webofficehours.comLet's learn together!Paul

Submitted March 24, 2020 at 10:47PM by pberesuita

Deep Dive into AWS for Node.js developers — IAM

https://medium.com/@gotoflorian.pro/deep-dive-into-aws-for-node-js-developers-iam-3f1578abf4a2?source=friends_link&sk=b6e7f44b9fea3cc66b7529cfceacbb55

Submitted March 24, 2020 at 10:25PM by wineandcode

Anyone else experiencing random class attribute undefined or JSON console output unparsed error with Maximilian Schwarzmüller's node-JS pre-coded Node JS files?

Title explains it all. Am on his 9th module (09- Dynamic Routes Advanced Models). Randomly, I'd get errors like typeerror: price not defined (product.price), or errors while adding products in my page, where my products JSON file gets automatically evacuated. When I exit Visual Studio Code and relaunch it, app seems to run just fine! Really hard to debug; try looking up on web, but can't wrap my head around the solutions there. Is it just some problem I'm facing, or something you've also experienced?Also, sorry if you're unfamiliar with the particular course, but from what I understand; his courses are some of the most practiced ones for basic NodeJs beginners, hence I directly refer to them. Can post code if necessary.

Submitted March 24, 2020 at 09:10PM by Percybhowal

Expressjs middleware not sending cookie to Angular front end.

I have my Angular front end calling my login function in my node express app and in the block of the controller, if my hashed passwords match, i set req.session.isLoggedIn = true;My session is set up using just the defaults before hitting any of my routes like so:​https://preview.redd.it/cbhqrrxmjoo41.png?width=458&format=png&auto=webp&s=8abb5df9a0cd9c2721b0705a2ff79596cdbfbcd3When i run my login on the front end, I am expecting the express session to send the cookie to my browser but nothing is there.Might be helpful to note that my node app is running on localhost:8080 and angular on localhost:4200.I do however get the cookie when I run my test request in postman so I am pretty sure it is on the Angular side. If this ends up being an Angular question, then I apologize for posting it in the wrong place.Any ideas? Thanks

Submitted March 24, 2020 at 08:28PM by NoControl712

Problem accessing the page while using puppeteer connection

I am trying to scrape information from an existing chrome page for learning purposes, using the puppeteer library. I have opened the chrome with debugging mode, received the ws url of the chrome page I am in, and connected successfully. Here is the connection code://open library const puppeteer = require('puppeteer'); //connect to excisting open page async function connectToChrome() { //Connect to excisting browser const wsChromeEndpointurl = 'ws://127.0.0.1:9222/devtools/page/5D6126455A889AA7D17B66C10729F352'; const browser = await puppeteer.connect ({ browserWSEndpoint: wsChromeEndpointurl }); The page which I have connected to is inside a url of a youtube video. My code's purpose is to find the amount of views of the video I am currently watching and log it to the console. When I have used this code while opening a new browser it was very easy, but now that I have connected to an existing page I don't really understand what is going on. I am not exactly sure how to access the information that is in the page, in a normal browser open you just open a new page, go to url, and save it to a variation. But right now I have no idea on which variation to call .$(xpath) to find the element//open library const puppeteer = require('puppeteer'); //connect to excisting open page async function connectToChrome() { //Connect to excisting browser const wsChromeEndpointurl = 'ws://127.0.0.1:9222/devtools/page/5D6126455A889AA7D17B66C10729F352'; const browser = await puppeteer.connect ({ browserWSEndpoint: wsChromeEndpointurl }); const [el] = await browser.page.$x('//*[@id="count"]/yt-view-count-renderer/span[1]'); const txt = await el.getProperty('textContent'); const txtJson = await txt.jsonValue(); console.log(txtJson); }; connectToChrome(); This code will return not understand the following line sentence, as it is undefined:browser.page.$x What would be the right syntax to access this element?

Submitted March 24, 2020 at 08:15PM by ProEngineerXD

[HIRING] (San Francisco) Healthtech Startup building a platform that supports Telemedicine for their patients (DOE 180K for Onsite Position)

Do Note that this is currently remote but any candidates will need to be able to work onsite after the crisis. They are currently unable to provide Visa Sponsorship for this role.Job DescriptionIn an ever more virtually connected world this startup is trying to bring healthcare into our modern world. They have developed a platform for doctors to provide telemedicine to their patients and allow them to get access to simple prescriptions that typically require patients to come to a healthcare facility to just get the prescription. This includes simple flu medication and even birth control. They are even actively working to help their patients get access to Covid-19 Tests. They are looking to bring on passionate Senior Node Engineers to work on their platform to help build new features to help their patients. They are extremely mission driven and are a great team!Required Skills & Experience5+ Years of Production ExperienceExperience working with Node and its frameworksDesired Skills & ExperienceExperience with HIPAA is hugeFrontend experience with JS frameworks like React are a plusExperience Deploying over AWSWhat You Will Be DoingTech Breakdown80% Backend Node Development20% Frontend React DevelopmentThe OfferCompetitive Salary: Up to $180K/year, DOEYou will receive the following benefits:Medical Insurance & Health Savings Account (HSA)401(k)Paid Sick Time LeavePre-tax Commuter BenefitApplicants must be currently authorized to work in the United States on a full-time basis now and in the future.Jobspring Partners, part of the Motion Recruitment network, provides IT Staffing Solutions (Contract, Contract-to-Hire, and Direct Hire) in major North American markets. Our unique expertise in today’s highest demand tech skill sets, paired with our deep networks and knowledge of our local technology markets, results in an exemplary track record with candidates and clients.Interested in applying? Please send a DM or an email with your resume to alec.soer@jobspringpartners.com

Submitted March 24, 2020 at 05:09PM by PythonRubyRecruiter

Average month price for node.js web server

Hi, how can I calculate the average price for 1 node.js web server depending of the traffic.I will use Heroku or google servers. I don't need the exactly price for those hostings, just someting generic for 1 month.

Submitted March 24, 2020 at 05:16PM by patilanz

Crypto.createHmac not properly encoding

Hello, I'm trying to replicate one of my Python3 files in nodeJS but im finding my createHmac is not returning the same encryption hash for the same secret and message as the pythons hashlib. Is this stackoverflow post inaccurate when it says that they are syntactically the same for the sha256 encryption? Below are my encryption codes.Node JSconst Crypto = require('crypto') // Standard JavaScript cryptography library signData = Crypto.createHmac('sha256', secret).update(message).digest('hex') Pythonimport hashlib hash = hmac.new(secret, message, digestmod=hashlib.sha256) signData = hash.digest().hex()

Submitted March 24, 2020 at 04:39PM by Blockchain_cenobite