Friday 31 January 2020

What exactly promises and async/await are for except for cleaner code?

I've just been getting into node and learning about those things. Is there a really much difference in execution time between three examples below?(This code is just one controller from my project written in three different ways)#1 Regular callback heavy one:exports.po_get = (req, res, next) => { poc.find() .exec(function(err, list) { if (err) { return next(err); } res.render('po.html', { list: list }); }); }; #2 Promises based oneexports.po_get = (req, res, next) => { poc.find() .then((list) => { res.render('po.html', { list: list }); }) .catch(next); }; #3 Async await oneexports.po_get = async (req, res, next) => { try { let list = await poc.find() res.render('po.html', { list: list }); } catch (err) { next(err); } }; How are they different apart from syntax?

Submitted February 01, 2020 at 02:25AM by radekpies

Mixing async/await and promises?

I am writing a controller that creates a user account. I wanted to do it using async/await but I have no idea how to save the object to db without using promises or callbacks.exports.signup_post = async (req, res, next) => { try { let hashedPassword = await bcrypt.hash(req.body.password, salt); let user = await new adminuser({ username: req.body.username, password: hashedPassword }).save() .then(it => { res.redirect("/"); }) .catch(err => { res.redirect("/cm"); }); } catch (err) { res.redirect("/cms"); } }; By the way, I am just starting to learn node/express, if you have any protips I would be glad to hear them.

Submitted February 01, 2020 at 02:27AM by radekpies

PNPM popularity is growing rapidly, is it time to ditch npm & yarn?

https://devspedia.com/pnpm-popularity-is-growing-rapidly-is-it-time-to-ditch-npm/

Submitted January 31, 2020 at 11:54PM by zkochan

Is Loopback 4 Ready?

Hi All,I used loopback 3 on a project - I really loved it at first and it helped me get off the ground very quickly, but as the project progressed, the lack of intellisense and some bugs have made me question my choice somewhat.I was looking at NestJS, but the rewrite will be significant.So, is Loopback 4 ready? It looks like it's missing some things before it gets feature parity with LB3 - does anyone have experience using LB4 in a production project?The most information I could find was this, but it's not really that clear on what state things are really at: https://github.com/strongloop/loopback-next/issues/1920Thanks!!

Submitted January 31, 2020 at 10:26PM by seventai

How to make background(parallel) requests in Node!

Hi! I want to run 10 requests at one time, and when all 10 responses will be received the loop will run another 10 requests. Is it possible in Node.js

Submitted January 31, 2020 at 09:27PM by AntonKrevedko

I built a simple node cli tool to display SNS messages on the command line

https://github.com/ziggy42/ontopic

Submitted January 31, 2020 at 09:16PM by ziggy42

Install PM2 without Node.js/NPM/Yarn with getpm2.com

https://getpm2.com/

Submitted January 31, 2020 at 06:32PM by tknew

Ultimate guide to concurrent logging in Node.js

https://medium.com/@gajus/ultimate-guide-to-concurrent-logging-in-node-js-4e47bd2eae37?source=friends_link&sk=fb85f85f4d9aa8cdec615c4529ba6685

Submitted January 31, 2020 at 06:05PM by gajus0

How does google form store data(schema)?

I was working with google form, I want to understand how does the google form stores data and dynamically create views when we edit data.I want to build a web page such that it user can dynamically create form and I need to store the input in such a way that I can easily fetch data from form and also allow client to retrieve data

Submitted January 31, 2020 at 06:09PM by ashish_choubey

Strapi in Docker on AWS ECS with Aurora serverless - how to setup?

/r/Strapi/comments/ewom57/strapi_in_docker_on_aws_ecs_with_aurora/

Submitted January 31, 2020 at 06:10PM by holy_serp

Express routes running *too* fast

Learning MEAN and I’m trying to use an NPM project to pull the dominant color from an image, to create a complimentary color palette for certain UI elements based on a random image that loads as the background of a “hero” section. Working with a local development environment, images are on my computer, not a cloud system, but even with async/await, the route finishes and renders the page before the script can load the image and pull the color. Am I doing it out of order? Should I put that part in a middleware that runs before the route? Is there a way to make the image load faster/route run slower?

Submitted January 31, 2020 at 01:13PM by serialcompliment

Debugging Node.js in Production with Diagnostic Reports

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

Submitted January 31, 2020 at 11:49AM by r-wabbit

Must have Gatsby plugins for a great blog

https://www.inkoop.io/blog/must-have-gatsby-plugins-for-a-great-blog/

Submitted January 31, 2020 at 11:54AM by jitendra_nirnejak

How to send information back to the Front end, AFTER functions triggered by a webhook are ran?

Lets just say I have a react front end, a node server/Postgress db, and a third party API that I'm getting data from to put into that db. I have an endpoint that lets me know when data is ready to retrieve, which in turn triggers a function to retrieve that data and insert it into my db, but how do I let my other endpoints/server know that insertion has completed?Like lets just say that ideally, after the webhook has been sent and the data has been retrieved, I'd like my React front end to hit a different endpoint(getTransactions) to get that freshly inserted data. How would I make sure that endpoint is hit after the webhook does its thing?If I use res.send on the /webhook endpoint that just goes to the third party API so the React front end doesn't have a way to know when its done that way. Is there away for my /getTransactions endpoint to wait for the database functions inside my /webhooks endpoint to finish before doing its thing?

Submitted January 31, 2020 at 07:40AM by Bruh_Reefion

TLS 1.3 - Get symmetric key

Hi!I'm trying (on the nodeJs server side) with TLS 1.3 to know (in clear/hex) the SYMMETRIC key generated on the server side with the Client Hello, anyone has a way to do this? I tried looking a lot but no-one apparently did it.Summar: CLIENT send TLS Handshake (Client Hello TLS 1.3 ) -> Server receives it, reply the Server Hello, with TLS 1.3, the server already know the symmetric key at that point (that will be used by both parties afterward), I just want to get it (as an arraybuffer or whatever format).Thanks everyone

Submitted January 31, 2020 at 08:12AM by AlexandroPixel

Thursday 30 January 2020

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

https://www.tutorialslogic.com/javascript?es6and7

Submitted January 31, 2020 at 05:37AM by ukmsoft

Docker Integration With Node.js REST API

https://www.c-sharpcorner.com/article/docker-integration-with-node-js-rest-api/default.aspx

Submitted January 31, 2020 at 05:57AM by amitcprabhu

Any good video tutorials for senior developers?

I don't think I've seen anything worth watching in the last few months. Most video tutorials show you how to make a really basic application that's horribly engineered. I am wondering if I missed out on something.

Submitted January 31, 2020 at 03:20AM by johnsnowdon

Arey you looking for a job change? Fill the form

Form Link

Submitted January 31, 2020 at 04:11AM by mehta-rohan

Should I put front end code into the web server?

I am learning NodeJS and I am wondering when I write my front-end (JS, CSS, HTML) code, should I put it under a folder called public under the NodeJS project or should I have NodeJS folder and Front end code in a different project respectively? Since I am new to developing web, I think I am confused about it. Also, If I should contain front-end code in NodeJS folder(server code), How do ReactJS Developers make that happen? Thank you so much

Submitted January 31, 2020 at 03:37AM by poream3387

Any book on how to make a production-level application?

Most video tutorials show you how to make a basic application that's engineered like a nuclear powered toaster. I am wondering if there's a book worth reading that will show me how to make something really complex and well-engineered, because it would be totally worthwhile.

Submitted January 31, 2020 at 01:49AM by johnsnowdon

Get all domains associated with IP address?

All Shopify stores run on IP 23.227.38.64. How would I approach finding all domains associated with that IP? There are a few sites that seem to provide it but charge to download the list, and people on the Shopify sub have pulled them before for research purposes, but I can’t find great info on how to go about it.

Submitted January 30, 2020 at 10:10PM by DasBeasto

What's your favourite rate limiting solution for express

The options on the official express security page are old and require redis and the link to the other option is dead. What other solutions are people using? Are the top npm results from google safe?

Submitted January 30, 2020 at 09:26PM by CloudsOfMagellan

Consuming webhooks with Node.js and Express

https://www.bearer.sh/blog/consuming-webhooks-with-node-js-and-express

Submitted January 30, 2020 at 07:42PM by frenchcooc

NodeJS on Windows

I work on both Mac and Windows (some enterprise clients require it) and wondered if anyone had useful links to increase Node performance on Windows - it’s another level of slow in comparison to Mac (Yarn, Webpack and Rollup are all considerably faster). I understand we see improved performance on a Mac because it’s Unix based but there must be more that can be done to avoid me throwing my Windows machine at the wall.

Submitted January 30, 2020 at 06:10PM by Billsy-D

Analyze Entities in real-time Calls using Google Cloud Language with Node.js

https://www.twilio.com/blog/analyze-entities-in-real-time-calls-google-cloud-language

Submitted January 30, 2020 at 06:25PM by lizziepika

Express js axios

hi when i try to send the result of my email send from my backend to the frontend i get the error "Access to XMLHttpRequest at 'http://maxcampbell.info/SendEmail' from origin 'http://www.maxcampbell.info' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request."​​​here's the code im using to call Axios"async SendEmail () {const response = await SendEmailService.register({email: this.email,message: this.message})console.log(response.data);axios.get('/StatusOfEmailSend').then(function (response) {if (response.data == "sucsess"){console.log("Sent email!");swal({title: "Email Sent",icon: "success",text: "your email has been sent",});}else {console.log("Error sending email!!!")swal({title: "Cannot send email",icon: "error",text: "your email has not been sent do to a server side error please try again",});}console.log(response);}).catch(function (error) {// handle errorconsole.log(error);}).then(function () {// always executed});}"

Submitted January 30, 2020 at 05:53PM by maxall41

Node library question

So i'm working on developing a web app where on form submit it collects the computers part information. I'm using this library https://www.npmjs.com/package/systeminformationSo far it works but I just noticed this in the library description "it is supposed to be used as a backend/server-side library (will definitely not work within a browser). It requires node.js version 4.0 and above. "Does this mean it won't work unless the computer on the website has node installed? Or will it work if I just host it on an AWS Server with node installed for example.

Submitted January 30, 2020 at 05:18PM by sideControl123

The people behind JavaScript: Allen Wirfs-Brock

https://javascript.christmas/2019/6

Submitted January 30, 2020 at 04:07PM by fagnerbrack

GraphQL-Subscription

https://overflowjs.com/posts/GraphQL-Subscription-With-Nodejs

Submitted January 30, 2020 at 04:27PM by denomer12

Any intermediate programmers here willing to answer a list of questions I have?

If you have Discord and wouldn't mind explaining some things that'd be great! I am taking a Udemy course on Node and have a sound baseline understanding of Node, but just have a list of questions. I know someone will ask why I didn't put them here, but it is a lot and I have follow up questions too! I also think itd be much easier to talk, cheers!

Submitted January 30, 2020 at 03:25PM by flat_soda_club

What’s easy and what’s hard and why

https://medium.com/javascript-in-plain-english/comparing-objects-in-javascript-ce2dc1f3de7f

Submitted January 30, 2020 at 11:15AM by Well_Gravity

Visualizing Logs from a Dockerized Node Application Using the Elastic Stack

https://blog.soshace.com/visualizing-logs-from-a-dockerized-node-application-using-the-elastic-stack/

Submitted January 30, 2020 at 11:13AM by branikita

Trying to list all Serverless monitor tools and resources.

https://haydenjames.io/top-serverless-monitoring-tools-serverless-resources/

Submitted January 30, 2020 at 10:37AM by modelop

puppeteer-proxy – Proxies Puppeteer Page requests.

https://github.com/gajus/puppeteer-proxy

Submitted January 30, 2020 at 10:02AM by gajus0

Introduction to parsing CSV files

https://youtu.be/9_x-UIVlxgo

Submitted January 30, 2020 at 09:37AM by morefoodmore

Building RESTful Api With Node.js, Express.Js And PostgreSQL the Right way

https://medium.com//building-restful-api-with-node-js-express-js-and-postgresql-the-right-way-b2e718ad1c66?source=friends_link&sk=b80aefe2c556de08d0eae1f2ab3aa01f

Submitted January 30, 2020 at 09:12AM by Fewthp

Possible to use a node server to privately/trustlessly execute a client-encrypted request to a 3rd party site?

e.g.a client app encrypts a reddit username/pass with a TEE key,the client posts this encypted payload to node server,node server passes this payload to a TEE function which decrypts & executes the request, and encrypts the response with a client public key before passing it back to client.Any way to do this while ensuring the server host can't monitor the request/response?

Submitted January 30, 2020 at 09:07AM by waterloo304

Wednesday 29 January 2020

PM2 Does Not Work with Node.js Installed Via Snapcraft.io

I'm just going to put this here incase someone else runs into a similar issue. Hopefully it will save someone some time.https://medium.com/@cazanator/pm2-does-not-work-with-node-js-installed-via-snapcraft-io-e4dc91fbcc72

Submitted January 30, 2020 at 06:39AM by Cazanator

Puppeteer as a web service?

I'm interested in putting up a puppeteer instance that I can use to scrape pages from a number of different web projects. Some are in python, some are in php, etc.I'm looking for a project that wraps puppeteer in a web api before I write one.If this project doesn't exist I'm happy to found it, but I can't believe this isn't a common use-case that has been done to death. My Google-fu seems to be failing me.

Submitted January 30, 2020 at 05:37AM by TarmacFFS

Is PHP/Node.js And Apache/Nginx on the same par?

I just started learning What these are and as far as I know, PHP is a framework for backend web server and Node.js is also for the backend webserver(Which is a runtime environment). But every time I try to see the difference between these from Apache Tomcat/Nginx, I cannot find the clearly explained articles. And I heard Nginx is used a lot in front of NodeJS. Are they all on the same par to be 'Web Server' Thank you so much

Submitted January 30, 2020 at 05:45AM by poream3387

8. Show success and error message using expressjs flash message

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

Submitted January 30, 2020 at 04:54AM by _lutfor

NPM debian buster HELL

hi all, Im writing here today bc of an issue with node package manager on debian 10.I have installed, nvm, yarn, downloaded from source, but no matter what condiguration is done i always get 'ERR_OUT_OF_RANGE'No, this is not me trying to access an index outside the bounds of an array.This occurs when i type npm -v or the sudo equivalent.I have tried node versions 10-13 with no success.Any help / prospective would be greatly appreciated.Error syntax buffer.js:585 slice: (buf, start, end) => buf.utf8Slice(start, end)

Submitted January 30, 2020 at 02:46AM by captn_gg

Using HTTP proxy with Puppeteer

https://medium.com/@gajus/using-http-proxy-with-puppeteer-b22ec7279b77

Submitted January 30, 2020 at 03:07AM by gajus0

How should we determine the resource requested in a REST API?

The same question was asked here 4 years ago w/ no answer, so I thought I'd bring it up as I'm running into this issue myself: https://stackoverflow.com/questions/30999003/how-should-acl-work-in-a-rest-apiI want to add an ACL to my middleware. My express logic is as follows :app.use(`api/v1/location/${locationIdRegex}`, passportAuth, locationRouter); my passport middleware authenticates the user by making sure their access token is correct. The next step is that I need to make sure that this user has access to the resource they are trying to modify.​The issue is that with REST, we put the resource in the path: "/location/${regex}". In another middleware function, we could look for the "location" string and then base our decision off of that. If we have another resource in the path, "/organization/${regex}/location/${regex2}", it gets much more complex. We can't just look in position 2 for "location" or "organization", because we have many resources.​What's the best way to determine which resource is being accessed?

Submitted January 29, 2020 at 06:39PM by fenwalt

Will nodeJS and socket.io be able to handle few hundreds of thousands of concurrent users in a chat app?

I need to build a basic and simple chat app (register, login, join room, send messages in rooms, send PMs to other users) that will serve approx few tens of thousands of people right from launch day with the possibility that it'll grow deep into the hundreds of thousands of users, and I need to know if nodeJS (which is a single instance app or whatever you call it) along with socket.io can handle this much data and users at the same time without hiccups, if it can't by itself then how can I make it work with maybe some library that will allow me to upload the same server app on multiple instances but guide them all to behave like a single instance (just throwing ideas here.. LOL)Thanks in advance :)

Submitted January 29, 2020 at 06:45PM by s_trader

Created a new chat app for the terminal ! Please tell me what you think

Hi everyone,So I created an NPM package called lmfao that you can install to chat with your friends through the terminal and give the appearance that you're working. I thought developers would especially like it to chat with their colleagues and pretend like they're coding so I wanted to know what you guys thought and whether I should keep working on it or not: https://www.npmjs.com/package/lmfaoPlease try it and tell me what you think! You can join public channels or create public channels to speak on, you can create password protected channels to speak with your friends only, and all these channels can hold 1,000 concurrent connections each. The only thing is that right now you basically have to create two terminal windows and login from both or split the terminal in half, and log in from both halves, so that you can message from one half and see all incoming inputs from the other. I discovered a new library based on runescript and C++ that would actually allow me to redesign the terminal so that the users would be able to message and see incoming messages from the same terminal window (like a "real" chat app) but at this point I don't know if it's worth putting the extra work being that I want to tackle other new projects.Please let me know what you think in general. About the concept, design, if you guys are interested. Would love to hear some feedback.CandideOrFuckingOptimism

Submitted January 29, 2020 at 06:48PM by candideoroptimism

Efficient way to scan just the first few lines from large files?

I need to scan through a lot of text files that are around 1MB or more. I just need to parse one short string value from a line that should appear in the first few lines of the file. I thought it would be best to read line by line until I find the value rather than loading the entire file. Is this the fastest way to do that that will safely close the file & line reader?function parseHeader (filename) { return new Promise(resolve => { let value // will hold value when found const input = fs.createReadStream(filename, 'utf8') const reader = readline.createInterface(input) reader.on('line', line => { if (!line.startsWith('value=')) { return // Not the line we want, continue. } value = parseValue(line) // Got the value, so cleanup reader.close() input.destroy() resolve(value) }) reader.on('close', () => { if (value == null) { // File was closed before finding line resolve(undefined) } }) }) } This only needs to run on Linux, so I shouldn't need to deal with any cross-platform filesystem issues.

Submitted January 29, 2020 at 06:22PM by spacejack2114

How to Implement a Linked List with Node

Hey guys!!Went ahead & created an in-depth tutorial showing you how to implement a linked list in JavaScript.Really hoping this is helpful for anyone getting their grounding in some data structures & algorithms for CS classes & such.Here's the link: https://youtu.be/lDSMCGr1fjg​Let me know what you think! :)

Submitted January 29, 2020 at 06:25PM by SynthesizeMeSun

Efficiently make HUGE amount of Puppeteer requests?

I’m building out a website that provides data about a set of other websites. I’m about to start the process of populating the initial data by scraping about 500k minimum websites using Puppeteer. The Puppeteer script fetches the given URL, grabs a few properties from the pages, takes a screenshot (currently after waiting 1s for better load), and then saving the screenshot and data to a MongoDB database.This seems to work fine one at a time and take about 1s (with or without the screenshot delay oddly enough). Now I’m wondering how to go about scaling this to (more) efficiently run this process on 500k websites. Worst comes to worst 500k is only 6 days of processing, I can drop it on an AWS instance and let it go, but presumably there’s a good way to parallelize this. But everyone seems to have different opinions on how with a lot of responses criticizing their approach.How would you go about it?On the plus side this is only a one off thing, or if I’m later auditing my data, otherwise one at a time will be the usual case.

Submitted January 29, 2020 at 03:59PM by ReactiveNative

I just made my first calculator using node.js! Any code feedback welcome.

https://github.com/SvizelPritula/MyFirstExpressCalculator

Submitted January 29, 2020 at 03:14PM by Svizel_pritula

GraphQL development trends for 2020

https://blog.graphqleditor.com/graphql-trends-2020/

Submitted January 29, 2020 at 02:54PM by oczekkk

Can't findByIdAndUpdate no error message

I'm trying to update an entry in my mongodb but somehow it fails. I get no error message, is not sucessfull the put does not seem to be successful. The network message shows no error code but also no header.I would really appreciate it, if someone could help me.Server:const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const app = express(); // Middleware app.use(bodyParser.json()); app.use(cors()); const sentences = require('./routes/api/sentences'); app.use('/api/sentences', sentences); // Handle production if (process.env.NODE_ENV === 'production') { // Static folder app.use(express.static(__dirname + '/public/')); // Handle SPA app.get(/.*/, (req, res) => res.sendFile(__dirname + '/public/index.html')); } const port = process.env.PORT || 5000; app.listen(port, () => console.log(`Server started on port ${port}`)); api:const express = require('express'); const mongodb = require('mongodb'); const router = express.Router(); // Get sentences router.get('/', async (req, res) => { const sentences = await loadSentencesCollection(); res.send(await sentences.find({}).toArray()); }); var Sentences = require("../../models/sentences"); // update sentence router.put('/:id', (req, res) => { Sentences.findByIdAndUpdate( req.params.id, { $set: {"annotations": req.body.annotations}}, function(err, result){ if(err){ return res.status(500).json(err); } console.log("RESULT: " + result); res.send('Done') }); }) async function loadSentencesCollection() { const client = await mongodb.MongoClient.connect( 'mongodb://localhost:27017/', { useNewUrlParser: true } ); return client.db('annotationDB').collection('sentences'); } module.exports = router; Model:var mongoose = require("mongoose"); var Schema = mongoose.Schema; var SentencesSchema = new Schema({ sent: String, annotations: Object }); var Sentences = mongoose.model("sentences", SentencesSchema); module.exports = Sentences; DataService:import axios from 'axios'; const url = 'http://localhost:5000/api/sentences/'; class DataService { static getSentences(){ return new Promise(async (resolve,reject)=>{ try{ const res = await axios.get(url); const data = res.data; resolve( data.map(sentence => ({ ...sentence, id: new String(sentence._id), sent: new String(sentence.sent), annotation: new Object(sentence.annotations) })) ); } catch(err){ reject(err); } }) } static updateSentence (params) { return axios.put(url + params.id, params) } } export default DataService; Updatefunction in vue:async updateSentence () { await DataService.updateSentence({ id: this.sentences[this.ids[0]].id, sent: this.sentences[this.ids[0]].sent, annotations: this.sentences[this.ids[0]].annotations }) this.$router.push({ name: 'Sentences' }) }, I logged the querry:Query { _mongooseOptions: {}, _transforms: [], _hooks: Kareem { _pres: Map(0) {}, _posts: Map(0) {} }, _executionCount: 0, mongooseCollection: NativeCollection { collection: null, Promise: [Function: Promise], opts: { bufferCommands: true, capped: false, Promise: [Function: Promise], '$wasForceClosed': undefined }, name: 'sentences', collectionName: 'sentences', conn: NativeConnection { base: [Mongoose], collections: [Object], models: [Object], config: [Object], replica: false, options: null, otherDbs: [], relatedDbs: {}, states: [Object: null prototype], _readyState: 0, _closeCalled: false, _hasOpened: false, plugins: [], _listening: false }, queue: [], buffer: true, emitter: EventEmitter { _events: [Object: null prototype] {}, _eventsCount: 0, _maxListeners: undefined, [Symbol(kCapture)]: false } }, model: Model { sentences }, schema: Schema { obj: { sent: [Function: String], annotations: [Function: Object] }, paths: { sent: [SchemaString], annotations: [Mixed], _id: [ObjectId], __v: [SchemaNumber] }, aliases: {}, subpaths: {}, virtuals: { id: [VirtualType] }, singleNestedPaths: {}, nested: {}, inherits: {}, callQueue: [], _indexes: [], methods: {}, methodOptions: {}, statics: {}, tree: { sent: [Function: String], annotations: [Function: Object], _id: [Object], __v: [Function: Number], id: [VirtualType] }, query: {}, childSchemas: [], plugins: [ [Object], [Object], [Object], [Object], [Object] ], '$id': 1, s: { hooks: [Kareem] }, _userProvidedOptions: {}, options: { typePojoToMixed: true, typeKey: 'type', id: true, noVirtualId: false, _id: true, noId: false, validateBeforeSave: true, read: null, shardKey: null, autoIndex: null, minimize: true, discriminatorKey: '__t', versionKey: '__v', capped: false, bufferCommands: true, strict: true, pluralization: true }, '$globalPluginsApplied': true }, op: 'findOneAndUpdate', options: {}, _conditions: { _id: '5e2e158f7aa2ac538a005281' }, _fields: undefined, _update: { '$set': { annotations: [Object] } }, _path: undefined, _distinct: undefined, _collection: NodeCollection { collection: NativeCollection { collection: null, Promise: [Function: Promise], opts: [Object], name: 'sentences', collectionName: 'sentences', conn: [NativeConnection], queue: [], buffer: true, emitter: [EventEmitter] }, collectionName: 'sentences' }, _traceFunction: undefined, '$useProjection': true }

Submitted January 29, 2020 at 02:30PM by TheFrankBaconian

6 Lessons learned from optimizing the performance of a Node.js service

https://engineering.klarna.com/6-lessons-learned-from-optimizing-the-performance-of-a-node-js-service-f163cac20473

Submitted January 29, 2020 at 12:58PM by r-wabbit

Easy Attach - a Library That Attaches a Debugger to Itself

https://github.com/hediet/easy-attach/

Submitted January 29, 2020 at 10:52AM by Gehinnn

How good is Node.js?

​https://preview.redd.it/5479mczp9pd41.jpg?width=1920&format=pjpg&auto=webp&s=6a6b9430cad57b47826c839773792d6cdf09f4bdNode.Js is the platform that web developers love to use to create the real-time, persistent web applications. For many, Node.js development has the capability to boost ROI or Return on Investment for many development teams. And, it offers an immersive user environment that is excellent.Big companies such as Yahoo, Netflix,eBay, and Walmart have used Node.js in their products. There are so many benefits when you use Node.js. Making an exhaustive list of reasons developers have embraced this technology would be far too long. So here are seven key reasons Node.js won’t be going anywhere:Reason 1 – Accelerates Your DevelopmentNode.js relies on Google’s V8 engine, which can transform JavaScript into native code at lightning speeds. Through this mechanism, Node.js can deliver efficient execution with scant memory requirements, even for data-heavy applications on the web. The versatility of Node.js allows for seamless usage on a wide range of devices, which is becoming an increasingly important consideration these days.Reason 2 – Best For Real-Time DevelopmentNowadays, almost all companies want to look at the customer’s information in the most up-to-date manner possible because understanding what the customer is looking for in real-time can help them improve stickiness, i.e. customer retention. Cutting out unnecessary steps is highly effective way to give the customer what they want. And, in recent years, web development teams are relying on Node.js to accomplish this task.Reason 3 – Streaming capacityHTTP requests and responses represent two distinct occurrences. In reality, they are the data streams. With Node.js, you can actually continue processing simultaneous to uploading. This alone can significantly affect the amount of time your users spend on processes. And who doesn’t love more time?Reason 4 – Node.js Is EverywhereAs a result of Node.JS, JavaScripts operates in both on the server-side and in the browser. Some organization feel that they need to shift things they developed for the browser to the server. If they were smart enough to opt for Node.js at the outset this migration is a breeze. It is much, much easier to account for the differences between JS browser and server tasks than to transfer JS to .net.Reason 5 – Ability to Build Applications With Just One Code BaseSynchronizing data between the server and the client side is automatic and becomes a lot easier with the help of Node.js. It is possible because the developers can write Javascript not only for the server but also for the client-facing portion of the app. An example of this amazing capability is Meteor, which was built over Node.js. As such, a change on the backend means an immediate identical change on the user-facing experience.Reason 6 – Acts As Proxy ServerNode.js offer a unique capacity to function akin to a proxy server. It is apt for aggregating data from the various source points from services that originate in different places.Node.js may provide a better option because you can structure it to act as a proxy server for your cloud server. This is especially helpful for small scale applications which may not do not warrant the necessary framework for a standalone, dedicated server. .Reason 7- Next Level Hosting AbilitiesNode.js is a big hit among the developers as it has some of the best features. It’s an equally big success in the market among fortune 500 firms. Ease of use for Node.js deployments is also increasing as Platform as a Service (PaaS) providers like Heroku and Modulus allow for quick node deployments using just a single command.Node.js development is not a silver bullet platform that can solve all problem in web development. But it can surely beats the historical alternatives and reliance on different programming languages outside of Javascript.

Submitted January 29, 2020 at 11:07AM by Zibtek_content

Is it possible to use EJS variables in EJS includes?

I recently started with ejs and I'm trying to make a sort of dynamic include, Id like to change the url of the template to include based on a variable.Something like:<% toLoad:"user" %>and then:<%- include('../partials/details-<% toLoad %>'); -%>I tried but I get Could not find matching close tag for "

How to update /usr/bin/nodejs?

I'm running a wiki on AWS EC2 using the Bitnami installation of MediaWiki. Since the wiki is going to be used by a lot of non-tech-savvy people in the future, I want to install the Visual Editor extension. Now this is all well and good, but the problem is that it relies on Parsoid, and that is where the problems begin.Parsoid refuses to start on my server. Now, I've narrowed this down to an outdated version of Node (v4.2.6 IIRC). So, I tried to use nvm to update it. Nothing. I tried using n. Still nothing. sudo nvm didn't work either. I did some digging and found that parsoid was trying to use the /usr/bin/nodejs path to run off, and running /usr/bin/nodejs --version returns v4.2.6, even though everything else has been updated to 12.14.1. And this is where I reach my wit's end, because no matter what I do I cannot get /usr/bin/nodejs to update. How can I do it?

Submitted January 29, 2020 at 09:58AM by CmdrNorthpaw

How to add RSS feeds data into MongoDB atlas server

I’m trying to retrieve content from various RSS feeds and save it into my mongo DB. I found code on the internet that does it with just one RSS url and it uses Crohn job to schedule it. I have decided to use setinterval for the time being. I want to know how I could request several RSS feeds at the same time.I also want to know would it be better if I had my feed request in a different file instead of the same that making a connection to Mongoose since I want to use several URLs and could I use feed parser node library to retrieve several RSS URLs?

Submitted January 29, 2020 at 08:58AM by pappermanfan

setInterval() infinitely fluctuaing in Node?

Hello all,In NodeJS, when I do something like the following:var initial = new Date().getMilliseconds() //Get initial Milliseconds setInterval(()=>console.log(new Date().getMilliseconds()-initial),1000) //Log the 'drift' every second The code starts to drift (as the console output shows)This seems to be the case with NodeJS only as if I were to run it in a console right here (on the chrome browser), I get tiny fluctuations that range from 0-2 but which don't continue to go up.In nodeJS, the fluctuations range from 1-infinite?Results

Submitted January 29, 2020 at 08:07AM by BarfAngel198

Tuesday 28 January 2020

5 NodeJS tools for fixture management

https://medium.com/@faboulaws/5-nodejs-tools-for-fixture-management-5296ffd47494

Submitted January 29, 2020 at 06:58AM by faboulaws

MongoDb fixture from Mongoose schema — Fakingoose with node-mongodb-fixtures

https://medium.com/@faboulaws/mongodb-fixture-from-mongoose-schema-fakingoose-with-node-mongodb-fixtures-83013238727f

Submitted January 29, 2020 at 06:57AM by faboulaws

First blog post on my personal website!

Hey everyone! I just made a portfolio website using Next js and wrote my very first article there. Do take a look at it! https://iabhishek.dev/post/building-a-multimedia-chat-app-using-expres-socketio-redis-and-docker-part-1I'd be very happy to hear from you guys regarding feedback. Thanks!

Submitted January 29, 2020 at 04:57AM by abhi12299

Server structure: Controllers, Service, Gateways and index.js.

Hey all,I have seen some code with src folder containing subfolders: Controllers, Service, Gateways and index.js. What is the meaning of this structure is there examples video tutorials demonstrating this server structure. I originally learnt all endpoints and logic go into the enter point file (server.js).

Submitted January 29, 2020 at 03:20AM by s_rash

How exactly a cluster receives incoming connections?

I'm just curious about this snippet of code from the docs because I understand that (at least in unix systems) two process can't use the same port and the exception is for child process who can access to the parent file descriptor. The docs says that NodeJS implements a RR (Round Robin) algorithm for load balancing, ok that have sense, but who is intercepting the incoming requests in order to execute the RR first? In the snippet I can see that parent process have no http code so he is not listening for http requests... I'm missing something. This is the image I have in my headnew request > something? > RR > child processI checked the source code of master and child and logically there is nothing that helps me to discover what is that "something".PD: Sorry about my english

Submitted January 29, 2020 at 01:17AM by dengue8830

6 Tips for Effective Use of Node on Android Devices

https://dzone.com/articles/5-tips-for-effective-use-of-node-on-android-iot-de

Submitted January 29, 2020 at 12:43AM by jcasman

Is there any good example of a Node.js UDP server that can stream videos so I can build a YouTube clone off of it with React?

Is there any good example of a Node.js UDP server that can stream videos so I can build a YouTube clone off of it with React? I need a good Node.js UDP server to implement a YouTube clone, so I was wondering if there's any repository that has a backend solution already implemented in Node.js.

Submitted January 28, 2020 at 11:37PM by johnsnowdon

How to install node 10.9 without nvm?

Like the title says, the work laptop I received is running version 8.9 and I would like to be running version 10.9.0 without installing the latest and using nvm. I have tried using npm install npm@10.9.0 and some variations of that but to no avail.

Submitted January 28, 2020 at 03:14PM by eurodollars

A fully typed CLI library with GUI support

https://github.com/hediet/ts-cli/blob/master/cli/README.md

Submitted January 28, 2020 at 01:02PM by Gehinnn

The performance implications of misunderstanding Node.js promises

https://eng.lifion.com/promise-allpocalypse-cfb6741298a7

Submitted January 28, 2020 at 01:08PM by aigoncharov

Emojion AI | Sentiment Analysis with Emojis 🔮

https://emojion-ai.glitch.me

Submitted January 28, 2020 at 12:36PM by mburakerman

A simple reddit api script that scrapes pictures

https://www.npmjs.com/package/reddit-api-image-getter

Submitted January 28, 2020 at 11:08AM by peterleder

What do you do to make sure that your node application is secure before sending it off to production?

Hey guys, I was wondering what kind of checks you do before sending your express node app to production.Im not looking for a list on what to do to secure your express node app, as ive basically went through each I could find, but more of a list on how to make sure your node app is secure.Do any of you do some sort of pen testing to your node express apps before production?Thanks in advance

Submitted January 28, 2020 at 09:48AM by livinglibary

A beginner’s guide to building a Docker image of your NodeJS application

https://maximorlov.com/a-beginners-guide-to-building-a-docker-image-of-your-nodejs-application/

Submitted January 28, 2020 at 09:50AM by _maximization

Troubles in Passport.js waters

compare-pdf: Standalone PDF file comparison node module

https://medium.com//compare-pdf-standalone-pdf-file-comparison-node-module-33222cace70f?source=friends_link&sk=686e231b77f293632b479ca449cf7511

Submitted January 28, 2020 at 09:12AM by Fewthp

[Project idea | Feedback needed] Node.js server provision application

Hey everyone, hope you all doing well.I've been thinking of building simple SaaS application which will with few clicks provision your Node.js server and make it ready for next deployment. Here are some of the core features.On setup you'll be prompted to select:Web server: Apache/Nginx/CaddyDatabase: MariaDB/MySQL/MongoDB/CouchDBRedis and other queue servicesQueue management, with supervisorFree SSL managementIntegration with GitHub, Gitlab & BitBucket,One click deploy, buildNo downtime deployments.All of these features won't be one time install, but manageable using the UI. Initial pricing for this will go up to $4-$10/month.I am interested in feedback, and will something like this be useful because.. Serveless. Is it worth building knowing that serverless is pretty huge nowadays?Thanks!

Submitted January 28, 2020 at 09:42AM by beganovichh

Creating a Node API and making money from it?

Hey r/node,I wanted to share a few thoughts I had about APIs and wanted to see if anyone resonates.As a developer, there are often only a few ways to make money:Build a full-fledged frontend + payment + authentication system to sell access to softwareSelling the intellectual propertyFreelancing / working for a companyIt got me thinking... there's actually a huge barrier before you can actually start earning from an API you've built. For us API developers, there should be an easy way to monetise our code without burdening ourselves with dealing with frontend + payment + authentication.To solve this, I'm building a platform that allows you to plug and play authentication, moderation, logging, etc. for your API whilst handling payments. Think of it like Airbnb but for your developer API.I would love to hear your thoughts / feedback having built APIs using Node in the past.Also, what's motivated you along the way if it wasn't for a commercial purpose.If you want to checkout what I'm building: https://www.codugh.com/Cheers!

Submitted January 28, 2020 at 08:38AM by tramador7

Changing output of Mongoose database query

Hi, Is it possible to change the output of a mongoose query during the generation, or is it only possible to change the return value in the app? Sorry if I can't articulate this better, but here is an example of what I have.const router = require('express').Router(); let Dataset = require('../models/practice.model'); router.route('/').get((req, res) => { const query = { inProduction: true }; const projection = { questions: 1 }; Dataset.find(query, projection) .then(json => res.json(json)) .catch(err => res.status(400).json(err)); }); module.exports = router; Which returns something like[ { "_id": "5de6647978e18605844b28e3", "questions": [ { "q": [ "something" ], "a": [ "something else" ] }, ... I would like have the output in the following format, so that the object's _id value replaces the questions property key.[ { "5de6647978e18605844b28e3": [ { "q": [ "something" ], "a": [ "something else" ] }, ... I can return this at the query level with Mongoose, or do I need to create a new object based on the output of the query?Thanks.

Submitted January 28, 2020 at 07:56AM by hey__its__me__

Find last elem in div Cheerio and Node.js

Is there an implementation of how to catch last elem in div (cheerio for Node.js) Like we have div containing another divs of one class. And we want to fetch data from this last div, but not to look over another divs

Submitted January 28, 2020 at 08:01AM by AntonKrevedko

Google File Picker API to Select Google Drive Files Example in Javascript

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

Submitted January 28, 2020 at 08:12AM by coderchrome123456

Streams In NodeJS

Best resources to learn about streams in depth?

Submitted January 28, 2020 at 08:22AM by __Nafiz

Monday 27 January 2020

12 factor config for node apps

So, I come from the enterprise Java/Spring world, and I'm wondering if the JS ecosystem has anything like Spring Config/Cloud Config, before I go off on a tangent and build it myself. My Google Fu is failing me. Spring config is really nice in that it allows you to prioritize application property resolution and define profiles for how your app should be bootstrapped.

Submitted January 28, 2020 at 02:30AM by general_dispondency

The way I like to setup my Node backend projects; w/Express, Objection.js + MySQL + Knex.js. Would like some feedback+ideas!

https://github.com/HappyZombies/express-backend-starterFirstly I'd want to thank you guys, I've been developing in Node for nearly 4 years now, I graduated from college last year and got a solid job as a Node backend developer. I asked a lot of dumb questions and have learned A LOT these past years and I have so much more to learn, so this sub holds a special place in my heart, thanks guys!Anyhow, onto the project...So there are many ways to structure a node project, but I think that the three layer architecture is the way to go. With a Routes, Services and Data layer model, you can seperate everything out and keep it all "contained". After many trails and errors I think that this architecture has always fit all of my use cases whenever I am developing any kind of express server.I'd like to share this project on how I like to structure my node backend projects for the purpose of further improving it. I hope that people follow and give constructive feedback on this project. Everyone has opinions on Node and it be great if everyone shared their ideas/what they think.Of course the architecture depends on what the node app is trying to do. But I think that if someone is using Express, Objection + some relational database; this is a good place to get started as it provides a solid building block to add whatever you want/need for your needs.Thanks again!

Submitted January 28, 2020 at 02:58AM by HappyZombies

Cluster with intervals

Hey guys,I have been working on a small node project, and I wanted to cluster it, which is new for me. Just in case this matters at all, I'm also using redis/postgres. My main question is what is the best way to handlesetInterval(() => ..., x); assuming I only this interval to be executing once every so often, and not once per thread (or am I just overthinking this)?Secondly, if anybody has a recommendation for a cluster framework/library, I would take that into consideration. I see a couple out there like throng, but yeah, if anybody has a recommendation. Probably doesn't matter too much in the end.Thank you.

Submitted January 28, 2020 at 03:20AM by TexasChiliBowel

New database being made after posting via node backend

I have got a node/express back end set up with mongoose to send POST requests to my database, and I'm testing everything with Postman. Whenever I send a POST request with the data, instead of it being put in the existing DB I have in the cluster, it creates a new DB inside the cluster called test. Any idea why and how to solve it?

Submitted January 28, 2020 at 01:29AM by Fizaraz

Gathering information with just a front-end

We need to get a website up and running ASAP.I'm currently building out a React front end to allow people to register and sign up.We need to record their email and other information they use to register but we don't currently have a server up and running yet and I don't want to put username and password of the database in the front-end code.I've thought about simply linking a button to a Google Forms or TypeForm and recording information there, but I'm curious if there are better ways to handle this problem.Thanks!

Submitted January 28, 2020 at 12:26AM by the_night_question

A GraphQL replacement

https://github.com/yosbelms/remote-func

Submitted January 28, 2020 at 12:31AM by yosbelms

Looking for a nodejs framework that could replace Django

Tl;dr I'm looking for a nodejs framework that could completely replace Django out of the box.Hi, I'm looking at building out a backend for what is currently just going to support a native app, but will eventually support other clients as well like web or even potentially hardware products.There's a lot of content to this app, including things like goals/milestones, activities related to those milestones, blog style posts, tips, etc, so having a CMS of some kind is important. We'd like this CMS to be mature, have user roles/permissions, customizations, etc.Scalability is also something that's been discussed in depth, as there is an expectation to grow quickly and we don't want to have to come back later and replace parts of our infrastructure.There's also many more complex aspects to the overall infrastructure including a machine learning aspect, we expect to need supporting microservices, and a robust cron/queue system. The latter 2 we would use Amazon services like SQS for example.For the API that would service the mobile app, I've been pushing to use Django and graphene so we can use GraphQL. Reason being, is that it comes out of the box with an admin panel that would do everything we need (particularly with the jet theme), the ORM is fantastic and integrates nicely with graphene, and it's mature enough to be battle tested and feature rich. As a bonus, there are even internal tools that have been hastily written in flask that could be easily ported to Django and managed all in one place.However, there has been interest amongst the team in using nodejs as it's new, more popular, and performs faster than Python at CPU bound tasks. There's also been concern that Django is just slow and not scalable. I've done a fair amount of research and so far I can't find any frameworks that compare to the "batteries included" nature of Django. I've also found no evidence to suggest that Django is unscalable. I've looked at sails, but I've seen mixed reviews of its ORM and it doesn't seem to have an out of the box CMS. I've looked at Keystone 5 but it seems immature, especially the CMS. I've looked at Strapi but it seems to be exclusively a CMS and also fairly immature.Perhaps my impressions of these frameworks have been wrong, and I recognize that I could run all this myself using express or possibly even just with several microservices, but we have a lot to do between now and our deadline for an initial version of the app (May). So Django is seeming like the best option to me.I would love for some people more experienced with nodejs to tell me why I'm wrong and some alternative framework would be better suited for my project. Or that I'm right cause let's be honest, everyone likes to be right haha.Thanks in advance, and sorry for the wall of text!

Submitted January 27, 2020 at 11:57PM by Brovas

How do get an array out of a csv file?

/* The contents of the csv file first slide CSV second slide CSV third slide CSV fourth slide CSV fifth slide CSV sixth slide CSV seventh slide CSV */ //CSV to JSON const csvFilePath="C:\\Users\\SOMEONE\\dev\\pptxGenJS\\slides.csv" const csv=require('csvtojson') let my_csv_object = []; let result = csv({ noheader:true, output: "csv" }) .fromFile(csvFilePath) .then((jsonObj)=>{ console.log(my_csv_object); return jsonObj; }) let csvArray = result //???? console.log(csvArray); I have read documentation. I don't understand how to get the value returned from the result section. Console.log does not display the contents of the CSV.

Submitted January 27, 2020 at 10:51PM by normandantzig

My first Node project with Spotify

Hello all,I have been learning Node.js over the past month and along the way I created a website that uses the Spotify API.The website shows your top played artists and songs over the lifetime of your account and over the past 4 weeks. The project was built entirely with Node and has no frontend framework. Any feedback or recommendations would be greatly appreciated.Also people ignore my terrible website design :) I am still trying to learn.Here’s the link to the website: Spotify Top PlayedHere’s the source code: GitHub source code

Submitted January 27, 2020 at 09:42PM by MajesticNectarine

How do you handle storing ids of Passport.js strategies, when using multiple strategies?

I want to use multiple strategies (local, google, facebook, twitter) and I am aware that passport.js returns an id from the service the user has chosen to sign in on.How do you handle this in your databases?Can I use the id returned from passport.js as the primary key of my users table or will there be collisions?Is it a bad idea to just have a strategy_id field in my users table, without storing which strategy it comes from?At the moment I'm thinking of having a user table, a login_strategy table (id, strategy_type) and a user_login_strategy table that relates the two tables.

Submitted January 27, 2020 at 08:12PM by SweatyHands247

ExpressJS Blogging System

I've recently finished a blog system in ExpressJS and thought I'd share. It uses Markdown formatting for post content and stores everything in a MongoDB Database.Current features include multiple user support (though they're all set to admins on creation), live markdown editing, publish/private posts and image uploading using express-fileupload.The back-end is a split up into controllers to keep adding features simple. Markdown content is converted on the back-end using ShowdownJS and then sent to the front-end.The front-end uses examples from Bootstrap's website and custom CSS, as well as some Axios scripts to post data to the back-endI'd like to develop this into a full blogging system with support for post comments, analytics, multiple categories and more.Feel free to test it out and leave any feedback/bugs you find :)https://github.com/dmdxv/express-microblog

Submitted January 27, 2020 at 08:28PM by DMDxv

puppet-canvas: HTML5 Canvas implementation for NodeJS backed by Puppeteer

https://github.com/pshihn/puppet-canvas

Submitted January 27, 2020 at 08:02PM by shihn

The Best Testing Tools for Node.js

https://developer.okta.com/blog/2020/01/27/best-nodejs-testing-tools

Submitted January 27, 2020 at 06:10PM by reverentgeek

Build a Weight Tracker App with Node.js and PostgreSQL

https://scotch.io/tutorials/build-a-weight-tracker-app-with-nodejs-and-postgresql

Submitted January 27, 2020 at 06:10PM by reverentgeek

Any advanced nodejs project (fun) for practice?

No text found

Submitted January 27, 2020 at 05:11PM by xxxxsomeguyxxxx

A simple 1337x, YTS and Nyaa.si torrent scraper API & App

Hi all.I'm a fairly beginner and recently I made a simple API that scrapes YTS, 1337x and Nyaa.si using node and express. The api also uses Redis to cache the search results for a fixed time.You can search for any torrents. The api also gives a basic "feeds"/torrents from the homepage of these sitesThe API is Here (Github) (Used Node, Express and Redis)and the App is Here (Github) (Used Nuxt/Vue)Don't know how to "deploy" redis so haven't deployed the app.Here's a demo of the very basic appWould love some feedbacks! :)Thankshttps://i.redd.it/8pim8l49jcd41.gif

Submitted January 27, 2020 at 04:22PM by BlackFeather97

Want to learn NodeJS microservices

Would anyone provide good learning resources to learn about nodejs microservices?

Submitted January 27, 2020 at 02:20PM by __Nafiz

A simplified Jira clone built with React/Babel (Client), and Node/TypeScript (API).

https://github.com/oldboyxx/jira_clone

Submitted January 27, 2020 at 02:22PM by mariuz

epoll is no longer cool

https://github.com/tokio-rs/mio/issues/923

Submitted January 27, 2020 at 10:05AM by aigoncharov

Dedicated Whatsapp Group for Node.js Developers to Share Resources About Node.js

Hey Guys I love Node so that's why I created this dedicated whatsapp group for sharing useful resources about node.js in this group. Kindly join this group and share your experience working with nodehttps://chat.whatsapp.com/J6PqwvZtCq0LBvuziU2dRk

Submitted January 27, 2020 at 10:11AM by coderchrome123456

What is the best Nodejs Framework for Class arrangement?

I'm looking for a framework for Node.js that can help me to create class resrvation system.Actually I'm looking for a framework to give the data including days and times of the class and session counts to it, then if I ask the day and time, it should show me is it busy or not!Also this framework should automatically arrange classes' times, for example If I give some thing like 'Wednesday, Thursday, Friday for 10 session time 10:00' it should calculate time and bussy time.I couldn't find suitable framework for that!

Submitted January 27, 2020 at 09:18AM by amirrezagh75

Inside node: What happens when we execute a script?

https://blog.s1h.org/inside-node-executing-a-script/

Submitted January 27, 2020 at 08:24AM by r-wabbit

Node & CSV in Under 2 Minutes

https://medium.com/teamzerolabs/node-csv-in-under-2-minutes-fc8c8b6d17b7

Submitted January 27, 2020 at 07:24AM by pmz

Sunday 26 January 2020

Building for Multi-Petabyte Scale with NodeJS

https://cribl.io/blog/building-for-multi-petabyte-scale-part-2/?utm_source=reddit&utm_medium=blog&utm_campaign=reddit

Submitted January 27, 2020 at 06:23AM by ledbit

How to implement a chatroom & online leaderboard?

Sorry if this is the wrong place for this, but I'm trying to learn more about the back-end, so for a personal project I'm trying to create a game that has a global chat and will store the user's final score (if good enough) on a global leaderboard (without them having to sign up).However I'm having a really hard time trying to understand how in the world I'm going to do this. My 'game' is a SPA using React on the front-end. I think (no idea) I'll use an express server + socket.io (for the chat?) + (some authentication method? sessions? jwt? oauth? firebase?) + postgres to store data (if I even need that). There are so many options and it's extremely overwhelming.How do I auth users w/o them signing up and allow them to chat or submit scores?How do I even go about creating a global chat room?Do I even need to use a postgres database? I'd imagine so, considering the leaderboard.So I feel like I have an idea of what I'll need to achieve this at the front and very end, but no idea in between. So I'd be greatful to get any wisdom or guidance to get me on the right track. Because I feel like if I just jump in blind, it'll be a disaster.React <> Express <> ???????????????????????? <> Postgres DB

Submitted January 27, 2020 at 06:58AM by theLastRising

Express Sqlite API, cannot access req.body after posting with node-fetch

I have four files,- srv.js: connects both routers to one file, does nothing but listen, use routers, view engines, and bodyParser/- frontend_routes.js: handles all the front end rendering, and redirects/makes requests to the back-end API routes- api_routes.js: the API routes, this hooks up to the sqlite db.- db.js: all database operations are performed in here.​So,I have a route `/create` which exists in the frontend_routes.js, it checks if all the required query properties are present, if not, continue to render the page, else, add all the query properties to an object named body, and then post it to the API route used to create a user, `/users`.the `/users` route exists in the api_routes file, and simply takes all the query properties and sends them to the db.js function.​However,in api_routes, req.body is empty. using postman to do this works completely fine, but doing it with node-fetch isn't. console.log(req.body) returns Object object, console.log(Object.keys(req.body)) returns nothing..? the body property exists if i console.log(Object.keys(req)), but is empty for whatever reason.​I've tried doing the post with the request, axios, and node-fetch libraries to no avail, here's the code for the post request:let body = {user_id: req.query.user_id,username: req.query.username,password: req.query.password,role: req.query.role}fetch("http://localhost:3000/users", {method: "post",body: JSON.stringify(body),headers: {"Content-Type": 'x-www-form-urlencoded'}})have tried with and without stringifying the body, with different content type headers.​and for the love of god, yes i'm using bodyParser, with urlencoded extended:true, I tried json as well with no luck.

Submitted January 27, 2020 at 06:14AM by Cola71t

Building a sentiment analysis app with Node.js

https://blog.logrocket.com/sentiment-analysis-node-js/

Submitted January 26, 2020 at 09:29PM by r-wabbit

How to do local debugging with AWS Layers

Hi, Maybe someone could help out with suggestions how to debug locally AWS lambda function with AWS layers, could it possible to install it locally like .m2 under Maven? Thank you

Submitted January 26, 2020 at 08:34PM by fatl1ar

Converting Raw Text into CVS

I am trying to read some data out of a gmail email. I can get into gmail and find the proper email then dump it to the console log. I have cleaned it up a bit, however I am not sure where to next with this. My end game is to use this data to power other actions so I will need to do math off the data in Node.Here is my SO post Period End,Date,Full Name,Hours,Tracking Name,TotalHours,Task 1 Hours, Task 2 Hours,Task 3 Hours,Task 4,Hours,Task 5 Hours,Task 6 Hours,Task 7 Hours,Task 8 Hours 4/21/2019 - 4/27/2019, CP, Hours-000104, 40, 1,5 ,10 ,0 ,0 ,0 1,5 ,0 ,0 4/28/2019 - 5/4/2019, CP, Hours-000103, 40, 1,0 ,10 ,10 ,0 ,0 1,0 ,0 ,0 5/5/2019 - 5/11/2019 ,CP ,Hours-000118 ,40 ,10, 1,0 ,10 ,0 ,10 ,0 ,0 ,0 5/12/2019 - 5/18/2019, CP, Hours-000233, 40, 1,0 ,10 ,10 ,10, 0 ,0 ,0 ,0 5/19/2019 - 5/25/2019, CP, Hours-000164, 40, 1,0 ,10, 10 ,10, 0 ,0 ,0 ,0 5/26/2019 - 6/1/2019, CP, Hours-000210, 40, 0, 0, 0 ,10 ,10, 10, 1,0 ,0 6/2/2019 - 6/8/2019 ,CP ,Hours-000211 ,40 ,5 ,20, 5, 5, 0 ,5 ,0 ,0 6/9/2019 - 6/15/2019 ,CP ,Hours-000234 ,40 ,10, 1,0, 10 ,0 ,10 ,0 ,0 ,0 6/16/2019 - 6/22/2019, CP, Hours-000251, 40, 0, 3,0 ,10, 0, 0 ,0 ,0 ,0 6/23/2019 - 6/29/2019, CP, Hours-000292, 40, 1,0 ,30, 0, 0, 0 ,0 ,0 ,0 6/30/2019 - 7/6/2019, CP, Hours-000310, 40, 0, 4,0, 0, 0, 0 ,0 ,0 ,0 7/7/2019 - 7/13/2019 ,CP ,Hours-000455 ,40 ,0 ,30, 0 ,10, 0 ,0 ,0 ,0 7/14/2019 - 7/20/2019, CP, Hours-000745, 40, 0, 1,0, 10 ,10 ,10 ,0 ,0 ,0 7/21/2019 - 7/27/2019 ,CP ,Hours-000709 ,40 ,0 ,0 ,10, 2,0 ,10 ,0 ,0 ,0 7/28/2019 - 8/3/2019, CP, Hours-000708, 40, 0, 2,0, 0, 0, 0, 10, 1,0 ,0 8/4/2019 - 8/10/2019 ,CP ,Hours-000851 ,40 ,0 ,0 ,0 ,40, 0 ,0 ,0 ,0 8/11/2019 - 8/17/2019 ,CP ,Hours-000886 ,40 ,0 ,0 ,0 ,40, 0 ,0 ,0 ,0 8/18/2019 - 8/24/2019 ,CP ,Hours-001133 ,40 ,0 ,0 ,0 ,40, 0 ,0 ,0 ,0 8/25/2019 - 8/31/2019 ,CP ,Hours-001311 ,40 ,0 ,0 ,0 ,40, 0 ,0 ,0 ,0 9/1/2019 - 9/7/2019, CP, Hours-001381, 40, 0, 2,0 ,20, 0, 0 ,0 ,0 ,0 9/8/2019 - 9/14/2019 ,CP ,Hours-001537 ,40 ,10, 1,0 ,20, 0, 0 ,0 ,0 ,0 9/15/2019 - 9/21/2019, CP, Hours-001604, 40, 0, 4,0 ,0, 0, 0 ,0 ,0 ,0 9/22/2019 - 9/28/2019, CP, Hours-001795, 40, 0, 5, 35, 0, 0 ,0 ,0 ,0 9/29/2019 - 10/5/2019 ,CP ,Hours-001956 ,40 ,0 ,0 ,20, 5, 5 ,5 ,5 ,0 10/6/2019 - 10/12/2019, CP, Hours-002020, 40, 0, 0 , 35, 0, 5 ,0 ,0 ,0 10/13/2019 - 10/19/2019, CP, Hours-002182, 40, 0, 2,0 ,10 ,10, 0 ,0 ,0 ,0 my end goal is something similar to this.

Submitted January 26, 2020 at 08:12PM by MeepMopBot

My first blog post on my portfolio website!

Hey everyone. Hope you are doing well. I'm sharing my first blog post on my personal website. Do check it out. All suggestions and feedbacks are welcome.https://iabhishek.dev/post/building-a-multimedia-chat-app-using-expres-socketio-redis-and-docker-part-1

Submitted January 26, 2020 at 05:42PM by abhi12299

Socket.io with async and await

I am new to web, and I am trying to learn how it all works by doing a small project for myself.I am trying to check if the string inputted by the user exists in the back end or not. And depending on the result I will show a message.//******// //Client// //******// const button = document.getElementById('button'); const textbox = document.getElementById('textbox'); button.addEventListener('click', function(){ if (checkEntry()){ alert("exists") } else{ alert("doesn't exist") } }); async function checkEntry(){ socket.emit('checkEntry', { entry: textbox.value }); var res; await socket.on('entryChecked', function(data){ res = data.result; }); return res; } //******// //Server// //******// io.on('connection', function(socket){ socket.on('checkEntry', function(data){ socket.emit('entryChecked', { result: check(data) }); }); }); function check(data){ //runs through an array and returns a Boolean } I am probably doing something wrong. Can you please correct my mistake and explain the reason behind it?

Submitted January 26, 2020 at 05:29PM by Derura

MODULE_NOT_FOUND Error

Hello, Whenever I try to start my application (A discord bot I made on my other pc) it throws this error in the console.PS C:\Users\PCUser> node .internal/modules/cjs/loader.js:983throw err;^​Error: Cannot find module 'C:\Users\PCUser'at Function.Module._resolveFilename (internal/modules/cjs/loader.js:980:15)at Function.Module._load (internal/modules/cjs/loader.js:862:27)at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)at internal/main/run_main_module.js:17:47 {code: 'MODULE_NOT_FOUND',requireStack: []}I'm pretty sure I installed every module, Is there someone that can help me?Thanks!

Submitted January 26, 2020 at 04:43PM by RedditAskings

A ready-to-use authentication solution for NestJS?

Hi everyone, I need your opinion on the subject.NestJS offers a guide on user authentication in their docs. It's based on the NodeJS Passport library. The original NestJS authentication docs are quite simplified. In reality, authentication is a bit more tricky.I wonder if it could be valuable if we include a ready-to-use authentication solution (similar to Auth0) to TypeCloud (a TypeScript cloud platform we are working on). What if you don't have to implement authentication from scratch? Let's suppose it's included for free. Is it worth it?

Submitted January 26, 2020 at 03:18PM by shurmanidze

[NETSJS] - how to return jwt token after create user

Docker image of GridDB NodeJS client

Hello people of Reddit,I was hoping if someone wouldn’t mind giving me a hand.I’m trying to create a docker image of a NodeJS instance with the GridDB client installed. To do this I need to compile the C client that the NodeJS client connects to. All instructions are for Linux and Windows and I’m having real trouble compiling this on a Mac.Does someone with 5 minutes fancy building an image and pushing it to DockerHub?Ive been trawling the Internet for fixes but I’m at my wits end.

Submitted January 26, 2020 at 01:31PM by astoneng

Persisting a login via JWT

Hey,I want to make an application with a mobile and web client. It will have a Node.js REST or GraphQL API.I've heard that the best way to authenticate when having independent frontend and backend is JWT. I've understood the basics of JWT, but I have a question about the persistence of your JWT.When the Token expires, what do you do? I can't just request another login, that would just be annoying.What do I do, when the data in the payload changes on the server? I would have to invalidate all existing tokens, because they contain wrong payload data. But then the user would have to log in again, which i want to avoid at all cost.So how do I avoid the need of logging in again when a token expires or I have to invalidate it because of change of data on the server?

Submitted January 26, 2020 at 12:46PM by thisw4y

Ways to reduce nodejs memory footprint ?

How to reduce default initial memory footprint of node.js runtime for memory-constrained environments ?I've only discovered --lite-mode and --optimize-for-size V8 options, but they have only slight impact. Are there other ways like disable implicit modules not used in my app ?

Submitted January 26, 2020 at 10:39AM by dunrix

How to backup your object storage

https://medium.com//how-to-backup-your-object-storage-29bfb9fe7584?source=friends_link&sk=2354a58d6aacccf139d0f0942f2c60c7

Submitted January 26, 2020 at 09:40AM by Fewthp

Split compression

Maybe my searches are wrong or it really just as easy as splitting the pre-compressed file and reassembling after; but I was wondering how to go about compressing into multiple parts. I'm using lzutf8 but can easily switch to zlib/pako/whatever.I've tested a few scenarios and the server-side compression/decompression is better performance and less complexity then other options (i.e. file storage with metadata pointer). The rub is that I want to specify the compressed chunk size and not arbitrarily split the data before compression. Should I just be splitting it up after I receive the compressed data or do any libraries actually support this?

Submitted January 26, 2020 at 09:49AM by TheLimpingNinja

Moongoose populate NightMare

I am trying to create social events hosting site, and for that, I am using mongoose.I have three different schemas. EVENT schema, USER Schema, COMMENTS schema.The problem is every time I make a comment on any POST, USERNAME is posted alongside.But as soon as I update the USERNAME in USER schema it's not getting reflected in previously posted comments by the said USER.I am lost and need help.var mongoose = require("mongoose");var passportLocalMongoose = require("passport-local-mongoose");var UserSchema = new mongoose.Schema({name: String,city: String,username: String,gender: String,token: String,about: {type:String,default:"Please edit your about..."},phone: {type:String,default:"NA"},imageFile: {type:String,default:"https://res.cloudinary.com/de189qjwo/image/upload/v1579693244/user_1_xpcx6a.png"}});UserSchema.plugin(passportLocalMongoose)module.exports = mongoose.model("User", UserSchema);var mongoose = require("mongoose");var commentSchema = mongoose.Schema({text: String,author: {id: {type: mongoose.Schema.Types.ObjectId,ref: "User"},name: String}});module.exports = mongoose.model("Comment", commentSchema);router.get("/", middleware.isLoggedIn,function(req, res){var id = req.user._id;User.findById(id,(err,user)=>{Event.find({},(err,events)=>{Task.find({}, (err, tasks) => {res.render("homepage",{user:user,event:events,task: tasks})})})})});I think there's issue with POPULATE please help.

Submitted January 26, 2020 at 05:38AM by samtrastic

Saturday 25 January 2020

Mongoose POPULATE NIGHTMARE

I am trying to create social events hosting site, and for that, I am using mongoose.I have three different schemas. EVENT schema, USER Schema, COMMENTS schema.The problem is every time I make a comment on any POST, USERNAME is posted alongside.But as soon as I update the USERNAME in USER schema it's not getting reflected in previously posted comments by the said USER.I am lost and need help.var mongoose = require("mongoose");var passportLocalMongoose = require("passport-local-mongoose");var UserSchema = new mongoose.Schema({name: String,city: String,username: String,gender: String,token: String,about: {type:String,default:"Please edit your about..."},phone: {type:String,default:"NA"},imageFile: {type:String,default:"https://res.cloudinary.com/de189qjwo/image/upload/v1579693244/user_1_xpcx6a.png"}});UserSchema.plugin(passportLocalMongoose)module.exports = mongoose.model("User", UserSchema);var mongoose = require("mongoose");var commentSchema = mongoose.Schema({text: String,author: {id: {type: mongoose.Schema.Types.ObjectId,ref: "User"},name: String}});module.exports = mongoose.model("Comment", commentSchema);router.get("/", middleware.isLoggedIn,function(req, res){var id = req.user._id;User.findById(id,(err,user)=>{Event.find({},(err,events)=>{Task.find({}, (err, tasks) => {res.render("homepage",{user:user,event:events,task: tasks})})})})});I think there's issue with POPULATE please help.

Submitted January 26, 2020 at 05:48AM by sachinssakri

Help thinking about eCommerce site logic

I am building an eCommerce site from the ground up and looking for some input on placing the logic on the server vs the client. particularly I am wondering if I should have the client let the server know how much to charge by calculating the cart total or if the cart should be sent to server and let the server handle calculating the total. My main thoughts are on security and exploit-ability I don't want to run into a situation where we gets orders that were charged at the wrong amount.So if anybody has some experience with this problem that would be appreciated.

Submitted January 26, 2020 at 06:00AM by 66633

Recommend me a simple database to store only my user feedbacks.

Is there any low cost online simple setup database for my need.

Submitted January 26, 2020 at 06:01AM by Chawki_

Vue CLI but all of its dependencies are dots (feat. Anvaka)

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

Submitted January 26, 2020 at 04:30AM by Richienb

Using node and rds mysql in AWS? Make sure you use mysql2 > 2.0.0

https://medium.com/teamzerolabs/node-rds-mysql-ssl-upgrade-am-i-impacted-b4fdfa7b4677

Submitted January 26, 2020 at 01:42AM by jack-tzl

Hosting a single markdown page

I am looking for a way to host a simple markdown page using node. I tried to searching online but everything I find is way to complicated for something simple. I know my google fu might suck but I thought this might be the best place to ask.

Submitted January 25, 2020 at 10:35PM by Not_A_MadScientist

How can I save a LIST in a Json or in a Txt ?

No text found

Submitted January 25, 2020 at 10:09PM by Bagaci05

Creating booking on Firebase

Guys I could use some help. I am a bit stuck.So I am trying to push an object to Firebase realtime databse and I have this piece of code.exports.create = async booking => {let id = guid.generate();let reservationNumber = await generateBookingNumber(booking.tripID);let trip = await tripUtil.getSingle(booking.tripID);await reference()    .child(id)    .set({ ...booking, reservationNumber, id }).then(() => {console.log('Successfully set');reference().orderByChild('id').equalTo(id).once('value').then(snap => {console.log(snap.val());return booking = snap.val();    });  });console.log(bookingCallback);// Variable and function for sending Twilio SMS// let holderPassenger = booking.passengers[0];// messages.sendOptionalConfirmationMessage(holderPassenger);// Variable and function for sending Email// emails.sendOptionalConfirmationEmail(booking, trip);return bookingCallback;}So I get the snapshot value inside .then() callback but I am not 100% sure how to return it so I can use it in email confirmation and to my function, because I am sending it to the client updated with the new data.

Submitted January 25, 2020 at 10:21PM by squizyt

Need advice on direction

It's been 8 months since I graduated as bachelor's in computer science. Currently working for past 6 months as back end developer. I have learnt and implemented business requirements.I have learnt and wrote production code using library(s) / tools - JavaScript, NodeJS, MongoDB, mongoose, Redis, socket cluster, request promise, AWS S3 upload , Akamai upload, Edge Grid cache cleaning , Agenda, RabbitMQ. Also, decent exposure to shell scripts.I know and understood the architecture and algorithm implementation logic of node js, MongoDB, Redis, Akamai cache, Agenda and RabbitMQ.I have used docker images a few times and debugged nginx bugs and routed traffic. I don't know anything on HAproxy, Kubernetes , etc.I am thinking to learn Kubernetes.I don't know what all I have missed in backend development and what to learn more ?My goal - I want to cover everything in backend development from just one instance of application, deploying that application, orchestrate it well, see and manage it well in peak times and crash downs.Please help or guide in realizing the goal.

Submitted January 25, 2020 at 09:24PM by LimpFroyo

nodeJs app which handels websockets with Express-wb production Issues !! HELP ??

​i m currently building an Express application capable of sending and receiving messages between many users , however when i switch to production env this basic example doesnt seem to work .the log.txt file in my server should log the message " socket estableshed : " whenever i send a message from my client . what bother me the most is that the connection is well estableshed and the message sent without error in the client browser , but never seems to arrive to the server .note that the Node app ( http ) runs behind an an HTTPS reverse proxy , and all the domain uses a cloudflair protection .note also that this small example works perfectly in my local env .does anyone have simular issues and solved it ?

Submitted January 25, 2020 at 08:30PM by nasgunner

[Middleware: cookie-session] How is 'req.session' change detected in this package?

From the Readme.md file,The middleware will automatically add a Set-Cookie header to the response if the contents of req.session were altered.Where is the implementation of detecting req.session change? Can somebody point me to the code or explain me how is this achieved?

Submitted January 25, 2020 at 08:12PM by zyx422

Memory Leaks Demystified

https://nodesource.com/blog/memory-leaks-demystified

Submitted January 25, 2020 at 08:15PM by r-wabbit

ndx-extended node debugger server and client cli on v8 debugger protocol

https://github.com/ecpy/ndx/blob/master/readme.md

Submitted January 25, 2020 at 07:46PM by pmz

Build a simple social network

Hey guys, I just wanna build a simple social network with node js, something just like a simplified version of reddit. Is there anybody who want to help me? Thank u

Submitted January 25, 2020 at 06:29PM by Raul_Garcia27

Datastructures in nodejs

Hi all i want to know what are the datastructures which are widely used in nodejs project or API development using node???

Submitted January 25, 2020 at 06:03PM by weirdorohit

Need help with folder & file management for socket.io events

Hello node.js and reddit community.​I work in MEAN stack atm. Express is only used to serve the index.html, after that, everything in app works through socket.io. I send a lot of events from client to the server, then update or query items from DB and send something back to the client in response. In bigger project, socket.io events take up to 2k lines of code and having them stacked up one after another inside the callback is hell.​io.on('connection', async (socket) => { const client = await mongodb.MongoClient.connect(dbUrl, dbOpti) const db = client.db(dbName) socket.on('someEvent', (someData) => { const res = await db.collection('someCollection').findOne({ _id: someData }) socket.emit('someEventRes', res) }) ... a lot more events later }) It's not exactly how my code looks but I think you get the idea. Right now thing I'm doing is creating 1 file functions (some-event.js in this case) and export it.​// some-event.js const someEvent = async (socket, db, someData) => { const res = await db.collection('someCollection').findOne({ _id: someData }) socket.emit('someEventRes', res) } module.exports = someEvent // server.js const someEvent = require() io.on('connection', async (socket) => { const client = await mongodb.MongoClient.connect(dbUrl, dbOpti) const db = client.db(dbName) socket.on('someEvent', (someData) => someEvent(socket, db, someData)) ... a lot more events later }) But this feels wrong. I'm passing the same socket, io and db over and over and the code still looks like ass. It's more easier to grasp, but I'm still not feeling it.​Any ideas how I can tidy this up? Thanks!

Submitted January 25, 2020 at 04:06PM by mmPvEhunter

Looking for good typescript + express tutorial and code review

Hello can you recommend any good typescript + express tutorial with SQL and nosql databases? Also looking at some other typescript + express tutorials I created this simple rest api example that you can find here: https://github.com/Tukczyns/express_ts_testCan you review this code and tell me if this is a good way or is it better to avoid spliting into class based services/controllers?Thanks in advance :)

Submitted January 25, 2020 at 03:26PM by Tukczyns

Get likes on a YouTube video real time with YouTube API and oAuth?

Hello all,I want to build a program that can display the like count on a YouTube video realtime with YouTube API and oAuth. I've coded a program so far that can get the likes the moment the program is run.https://github.com/DGKSK8LIFE/youtube-notification-bot/blob/master/app.jsThe code works but I don't know where to go from here. I've tried using while and for loops, but of course, that did not work. I've looked over this question in Stack Overflow (https://stackoverflow.com/questions/53621309/how-can-i-retrieve-subscriber-count-from-youtube-api-without-oauth) and I got an idea to use it without authentication, but I want it with oAuth. Would I have to use cheerio? If so, how would I use that?Thank you all very much.

Submitted January 25, 2020 at 03:15PM by gallojsantiago

Stuck with passing json web token when logging in

Hi,project filesI have a simple login project that provides a user with a jsonwebtoken once they have logged in. Once logged in the user should be forwarded to a hidden route. The system works in postman but when I render it in the browser I always receive 'Access denied'. I don't know how to pass the webtoken over once i've logged in.I've tried looking into cookies to do so and i downloaded a few packages but I just can't get it to work. The files are above if you want to download and view it in the browser. Alternatively, the code where the issue arises from is:BACKEND THAT PASSES THE WEBTOKEN IN THE HEADER router.post('/login', async (req, res, next) => { //CHECK IF EMAIL EXISTS IN DATABASE const user = await userModel.findOne({ email: req.body.email }) if (user == null) { return res.send('Email doesn\'t exist') } const validPassword = await bcrypt.compare(req.body.password, user.password) if (!validPassword) { return res.send('Invalid email or password') } //CREATE AND ASSIGN JSON WEB TOKEN const token = jwtoken.sign({ id: user._id }, process.env.TOKEN_SECRET) res.header('authToken', token) res.redirect('../posts') }) ​CHECKS IF USER HAS TOKEN const auth = async (req, res, next) => { const token = req.header('authToken') if (!token) { return res.status(401).send('Access denied') } try { const verified = jwToken.verify(token, process.env.TOKEN_SECRET) req.user = verified next() } catch (err) { res.status(400).send('Invalid token') } } ​HIDDEN ROUTE - CHECKS THE BLOCK ABOVE TO SEE IF A WEBTOKEN EXISTS router.get('/', authToken, (req, res, next) => { res.send('User logged in') }) ​I don't get how to make this work outside of postman and in my actual browserI think I need to pass it with cookies somhow...but I cant figure out howThanks.

Submitted January 25, 2020 at 02:40PM by stuckloggingin

How to add json Array of subdocuments into MongoDB?

Hi,Just dipping my toe into MEAN with a small project to see how I can start using node and mongo instead of our normal c#, IIS and SQL server.I'm slowly getting my head around the NOSQL way but I'm stuck at what I think should be a pretty easy thing. I have written a model that has a main shema and a 2nd schema that will be subdocuments.​const mongoose = require('mongoose'); const batchDetailsSchema = mongoose.Schema({ account: {type:Number, required: true}, project: {type:String, required: true}, description: String, amount: {type:Number, required:true}, extRef: String }); const batchSchema = mongoose.Schema({ batchID: String, description: String, uploadedBy: Number, uploadedDate: { type:Date, default: Date.now() }, batchDetails: [batchDetailsSchema] }); module.exports = mongoose.model('Batch', batchSchema) I have a user upload a csv file, this file matches the batchDetailsSchema, and it contains 3000 rows.I have the csv file convert to a json object but I can't work out how to add all of these objects in one go as subdocuments of the batch.​I have it working for one using push:Batch.findOne({"_id" : newBatchID}, (err, doc)=>{ doc.batchDetails.push({ account: results[0]['account'], project: results[0]['project'], description: results[0]['description'], amount: restults[0]['amount'], extref: results[0]['extref'] }) doc.save(); So I suppose I could loop through each row of the csv and add it this way but that's 3000 calls to the database when I am sure I'm missing the simple way to just use the jsonObject.Any help would or links links to some decent tutorials but be really appreciated.Cheers

Submitted January 25, 2020 at 10:48AM by aBitOfCloud

Where should I keep the CREATE TABLE script?

Hi, I have a plan to create an API that uses MySQL as a database. I have never used SQL as a database before so I don't know where to keep the CREATE TABLE script. Should I just keep it in the API and run the script every time the server starts? Or should I just create a script and run it only when I want to update the schema?

Submitted January 25, 2020 at 10:56AM by 1t2t3t4t

Building a Production - Ready Node.js App with TypeScript and Docker - Cloudnweb

https://cloudnweb.dev/2019/09/building-a-production-ready-node-js-app-with-typescript-and-docker/

Submitted January 25, 2020 at 11:09AM by GaneshMani

Reddit Clone

Hey, do u know a good reddit clone built in node.js? Maybe some youtube videos or an online course! Thank u!

Submitted January 25, 2020 at 09:57AM by Raul_Garcia27

Friday 24 January 2020

Is there a way to decide if a JS file is sent based on device type?

I might be using a masonry package but it isn't necessary for mobile (small) devices, so I'm wondering if upon the http request I can choose whether to send the package or not?

Submitted January 25, 2020 at 05:49AM by FIREATWlLL

Microservice connectivity with docker & k8

How do you guys keep your running instances talking to each other? I’m trying to wrap my head around this and it just feels dumb. Lets say you have an authentication/user service and another service called posts. How is the relationship of the models kept in both of the services and how do you handle the connection?

Submitted January 25, 2020 at 03:56AM by salttis

Noob question about public directory in express.

app.use(express.static(path.join(__dirname, "public"))); I have to use EJS for a school project and I'm having trouble getting my images to load. My stylesheets and other js scripts are also in the public folder, obviously, and they are working fine. Why the hell isn't it grabbing my images. It keeps throwing a 404.

Submitted January 25, 2020 at 12:09AM by AntipodalBurrito

Need some advice on how to scale node.js backend using docker

I have a docker instance running my API, but its only using one process I think.I have 4 cores.

Submitted January 24, 2020 at 11:02PM by chovy

Whats logic of PUG (expressjs template engine) to use "p #{myvar}" instead of

#{myvar}

?

Faster writing templates? perfomance? For me is just adds unessary confusion.

Submitted January 24, 2020 at 09:45PM by xoxaxo

Advanced Node.Js: A Hands on Guide to Event Loop, Child Process and Worker Threads in Node.Js

https://blog.soshace.com/advanced-node-js-a-hands-on-guide-to-event-loop-child-process-and-worker-threads-in-node-js/

Submitted January 24, 2020 at 09:50PM by UncleBen2015

Architectural Question for Testing

I currently have an express server running and am using mocha for my tests. I am using Mongoose to connect with MongoDB.I want to have all my tests use a separate database for testing so that they don't conflict with the real database but I'm unsure of exactly how to set it up. I want to be able to test the routes of my express server and also make database queries in the tests to make sure everything ran as properly (post to "/create_user" route and query the database to make sure user is actually there).I'm unsure of exactly, generally speaking, how to set this up. I've tried a few different ways but none seem very efficient.Can anyone suggest a general idea of how would one go about this?Thanks!

Submitted January 24, 2020 at 05:58PM by the_night_question

URL shortening and redirecting service using MongoDB

https://github.com/JaimermXD/url-amylase

Submitted January 24, 2020 at 05:49PM by JaimermXD

Dialogflow + Node.js send SMS or Email

Hi there,I am building a simple voice assistant with Dialogflow, a kind of smart FAQ.Let's say I ask the Assistant:Me: Where is the nearest grocery shop?Google: 5 min away. May I sent the location via SMS or email?With Node.js is that possible to connect Dialogflow to an SMS or email service?I am not Node.js developer but I heard it can be done with Node. I really would like to understand how it works.Thank you

Submitted January 24, 2020 at 05:16PM by SottileDesign

Database / models abstraction and structure.

I have a high throughput web server and am trying to create a nice abstraction between the DB and core server logic. Right now I have the following structure:/api (routes)/servicesWhere the services have code for the DB, how does one create an abstraction over a few DBs (BigQuery & FireBase)?

Submitted January 24, 2020 at 03:51PM by ydennisy

Triggering side effects in a graphql api

I'm investigating adopting GraphQL for our system but our system requires a ton of side effect triggers including but not limited to: zip/unzip files, req other back end services, put files in a caching layer, parse those files on req, etc. With REST this is obvious since you can place this logic in controllers and off you go. I peeked through the graphql docs and didn't see anything that would help with this.Would we need to keep some REST endpoints around for all these side effect use cases? FWIW I'm a front end guy so I could be missing something obvious

Submitted January 24, 2020 at 03:00PM by Peechez

I just published a tutorial on how to develop and distribute private modules keeping full control by not using a registry. What do you think? Are there better options?

https://stackoverflow.com/a/59898507/4579271

Submitted January 24, 2020 at 02:38PM by sunknudsen

Am I the only one not hyped about deno js?

Recently discovered that Ryan Dahl is creating a new typescript runtime which should replace node.Typescript is amazing and the node modules can get heavy I agree to that.But is it really necessary to make a new runtime instead of improving the current one ?

Submitted January 24, 2020 at 02:14PM by gilaila

Display RSS Feed on Vue.js as a front end

Hey guys,I've been struggling to display this RSS Feed ( https://www.google.ie/alerts/feeds/10663948362751557705/4511034072220974544 ) on my Vue.js application. I know there's multiple ways to create HTTP requests in node but was wondering what is the best approach in order to avoid the CORS policy?Is there any good examples or tutorials that I can follow so I can display this RSS Feed? I am new to Node and I've been trying for months to do this. Thank you.

Submitted January 24, 2020 at 01:55PM by RyboXBL

Recommend a free resource for learning core NodeJS

Hi everyone, i know my way around client side javascript and i'm just getting started with NodeJS.However, i find most tutorials online either lack continuity or they focus on third party modules.Nodejs.dev is beginner-friendly but very shallow and a bit disjointed.Flavio Copes' NodeJS handbook has the same content as NodeJS.dev.The official Node API docs contain the kind of content i'm looking for but they're riddled with FRUSTRATING repetition. In fact, once I understand the workings of NodeJS, I plan to edit the docs into more concise, readable, non-repititive form to save future devs the trouble.If you know a good resource that's got good content on Node modules please share. I could really use your help right now.

Submitted January 24, 2020 at 12:52PM by iMorphed

RapidAPI adds GraphQL APIs to it's offer

https://blog.graphqleditor.com/rapidapi-graphql/

Submitted January 24, 2020 at 11:42AM by oczekkk

Anonymous web scrapping with Node.js, Tor, Puppeteer and cheerio

https://medium.com/@georgegkas/anonymous-web-scrapping-with-node-js-tor-apify-and-cheerio-3b36ec6a45dc

Submitted January 24, 2020 at 10:22AM by georgegkas

Global survey: The State of Microservices 2020

Hello everybody!I’ve been posting here on r/node for a while now and, knowing how awesome this community is, I decided to call for your help. 🙏 I’m trying to reach out to all microservices fans (and antifans) out there and ask for your opinion on this architecture.We’re preparing a vast study on how developers use microservices, what are the current trends, preferable languages, tools, design patterns, etc. The whole research project is backed up by ZEIT, Cooperpress (yup, the folks behind the Node Weekly and JavaScript Weekly) and Richard Rodger (yup, the author of "The Tao of Microservices"), so you can believe me that it's no scam. 😉No matter if you work in a corporation, small company or freelance – we would love to hear from you. We’ve prepared a short, 5-minute survey, and I hope that you’d like to contribute.👉 The State of Microservices 2020 SurveyThe report based on the results of the survey will be available to download for free in March and I’m sure it will be a nice study for the whole IT community.Help us, Node developers – you’re our only hope! 👸🏻

Submitted January 24, 2020 at 10:55AM by placek3000

How to retrieve data from newsAPI and display on React

So I’m trying to retrieve data from a news API (BING for now) via Express through get (route) and then display it on my React front end. I know it seems really uncomplicated and it probably is but my code is a complete mess. I have very little knowledge on React/express and this is part of an assignment I’m doing. Not only do I have an issue w the routing and retrieval of data. I also have an issue with my front end components.I have used several similar projects on the internet as a reference but their projects are either overly complicated/they use a third party application like pusher. Is there any simple non complex way of doing this? I’ll post my codes in code sandbox in a moment.PLEASE HELP. DEADLINE. Possibly explain my mistakes like I am a second grader.REACT CODE: https://codesandbox.io/embed/floral-sea-k1tr3?fontsize=14&hidenavigation=1&theme=darkSERVER ROUTES: https://codesandbox.io/embed/musing-surf-o3ee2?fontsize=14&hidenavigation=1&theme=dark

Submitted January 24, 2020 at 08:08AM by pappermanfan

Server won't start when trying to use socket.io-emitter

I'm trying to emit a message to one of my sockets from a non socket process... Basically I have the sockets which have a bunch of rooms and users, and I want to make an API GET call to express and from within that GET call emit a message to the sockets, and according to socket.io's docs you can use socket.io-emitter to emit messages from a non socket process.. So I installed it and when I try to require it and start the server (even when I only require without actually trying to use it) the server just won't start, it give a long error message...I'm erring on mobile so in an hour or so I'll add my code and the error message, but if anyone has a good tutorial or an example project on github (not the official ones) then I'd love to have a link to that, thanks :)

Submitted January 24, 2020 at 07:21AM by s_trader

How do you store oauth token?

I am learning to build express based app. Here's what I did:Created oauth flow to access data. After getting the auth token I made a request to that service and as expected I did receiveOAuth the data but when I made the same request with another browser those auth tokens were accessible to everyone.According to my coding, if I get tokens and store it in a variable then it's accessible to all upcoming users. I want to know how you guys perform this task. Do you store it in DB then get data from client headers and verify it or store the tokens in client headers?Please let me a process flow which is more suitable and secure.

Submitted January 24, 2020 at 07:29AM by ExhaustedWildcat

Thursday 23 January 2020

Who are the best (at least top) instructors/teachers for Node.js?

I am a javascript developer. I want to become a full-stack so I decide to learn node js. someone help me to choose the best teacher for learning node.

Submitted January 24, 2020 at 03:44AM by ap_goo

Highly Available Node

https://josh.blog/2020/01/highly-available-node

Submitted January 23, 2020 at 11:43PM by jshbz

Ask Reddit: What's the oldest node version you got running in production?

I have a couple of 6.4.0 running at one of client's.Rest are on 8 or 10.People do not dare touch the 6.How about you guys?!

Submitted January 23, 2020 at 11:37PM by jack-tzl

February 2020 Security Releases

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

Submitted January 23, 2020 at 10:05PM by dwaxe

Server running locally but not when its deployed to Heroku

Hey guys and girls! I have had this problem for quite a sometime now and I can't to figure it out. I am quite new to coding and I am now reaching out to the community .This the question I posted on Stackoverflow with no luck. There maybe be a couple of differences in the code since I posted it but I still have the same problem.Thanks in advance :)https://stackoverflow.com/questions/59266189/heroku-app-works-locally-but-not-when-deployed?noredirect=1#comment104740762_59266189

Submitted January 23, 2020 at 09:28PM by tayo2501

Developing algorithms [interview question]

Hi folks! I'm looking for any resources that I'll be required to code algorithms (JavaScript ofc) based on the question. For example, I'm gonna soon take an exam that sent from adaface bot (adaface.com) . Most questions are written code that asks the output etc, but in the end I am asked to create some algorithm. For example (took from their sample test) the last question is this: "Data analysis for Netflix Favorite Movie"* We are building a Netflix clone where users can stream movies. Our service tracks and logs usage for each user. Each log contains the name of the movie, length of the movie (in minutes) and number of minutes of the movie watched by the user. Can you help with some data analysis?My question is where I can find such quiz or practices?

Submitted January 23, 2020 at 07:13PM by j_abd

ObjectionJS

Hey guys,I have this class:class Item extends Model { user!: User; asset!: Asset; shares!: number; static tableName = 'items'; static idColumn = 'id'; static relationMappings = () => ({ user: { relation: Model.BelongsToOneRelation, modelClass: User, join: { from: 'items.userId', to: 'users.id' } }, asset: { relation: Model.HasManyRelation, modelClass: Asset, join: { from: 'items.assetId', to: 'assets.id' } } }); } and I wanna create a new Item. I want to check if the user and the asset exists. I tried to retrieve the user and the asset from the database before and do:await Item.query().insert({user, asset, shares: 0})but the ids in the table are still null then. I dont understand what the issue is here. Anyone got advice for me?Basically I would like to do something like:INSERT INTO case (scenario_id, employee_id) SELECT s.id, e.id FROM scenario AS s CROSS JOIN emplopyee AS e WHERE s.`key` = 'UC01' AND e.employee_no = '0001'

Submitted January 23, 2020 at 06:27PM by roconf

When using redux in an app when is it good to use redux.

I understand that it is never good to add another layer of complexity by replacing local state with it.I read this post (https://medium.com/@dan_abramov/you-might-not-need-redux-be46360cf367). It talks a lot about when not to use it but not much about to use it.I know that I should be using redux to control state that could be theoretically undone by the user.But where else?

Submitted January 23, 2020 at 05:30PM by Administrator101

A fun side project I made in nodejs: Nova, a programming language built for powerful simplicity

https://github.com/dan-online/Nova

Submitted January 23, 2020 at 05:00PM by DanCodes

Node-schedule vs. Cron?

Im trying to build a node server that will need to schedule a bunch of tasks and I’m trying to figure out the difference between node-schedule and node-cron. It looks like their functionality is pretty similar it’s just that node schedule says:“Note that Node Schedule is designed for in-process scheduling, i.e. scheduled jobs will only fire as long as your script is running, and the schedule will disappear when execution completes. If you need to schedule jobs that will persist even when your script isn't running, consider using actual cron.”What does that mean exactly?If it helps here are my exact requirements.1) Receive a task and time (every 30 minutes or at 4pm daily) via Ajax to my Node server on Heroku.2) Store the task data, then create the cron-like scheduled event to run at the given times.3) At the given time, execute a certain event (an outgoing HTTP request).4) If the server goes down for any reason, on start grab all saved tasks from the database and reinitialize them.Note: I want this to be able to scale to a lot of scheduled tasks if needed.Does either package make more sense for my usage if I’m saving the task data anyway, what is in-process scheduling in this regard?

Submitted January 23, 2020 at 03:21PM by ReactiveNative

YALFWT - Yet another library for worker-threads (typescript).

Bring In The Bots, And Let Them Maintain Our Code!

https://hackernoon.com/bring-in-the-bots-and-let-them-maintain-our-code-gh3s33n9

Submitted January 23, 2020 at 02:57PM by patrickleet

Securing an end-point with cookies in addition to CORS

I have a piece of javascript code that will be added to a existing webpage, which sends a request to a remote server end-point. Since this end-point is visible on the client-side code, it's basically public and can be exploited.I set up the CORS to only send response to the request coming from this specific domain.However, apparently this is not secure alone, as people can spoof the headers and get the response.As a solution to this, I though of creating another end-point to set a cookie if and only if this request is sent from this specific domain.So, my questions are1- Is it possible to set a cookie if the req is sent from a specific domain?2- I believe the first question is possible to implement, but likewise, people can fake the domain that the request is sent and get the cookies in return. However, can they make use of these cookies the way they can fake the headers to breach the CORS security?3- Is this a proper solution at all?4- If not, what measures can I take to make this public end-point safer?I have no access to the server of a that page where my code will be added. Otherwise I would send the request from server instead of exposing it in the client.

Submitted January 23, 2020 at 01:34PM by eligloys

Turning txt to xlsx, out of memory ?

Hi. I'm trying to turn 40 .txt files to .xlsx. I don't want to do it manually, and i haven't found any library to do so. Here's my code.var fs=require('fs'); var Excel=require('exceljs'); var reader = require ("buffered-reader"); var FOLDER ="./../Data/ING5"; fs.readdir(FOLDER,function(error,folders){ folders.forEach(folder=>{ if(!folder.includes(".txt")){ fs.readdir(FOLDER+folder,function(er,list_files){ var has_excel=false; var clean=""; list_files.forEach(file=>{ if(file.includes(".xlsx")) has_excel=true; if(file.includes("clean.txt")) clean=FOLDER+folder+"/"+file; }) if(!has_excel){ console.log(folder); var workbook = new Excel.Workbook(); var sheet = workbook.addWorksheet('sheet 1'); var r=1; new reader.DataReader (clean, { encoding: "utf8" }) .on("error", function (error){console.log (error); }).on ("line", function (line, nextByteOffset){ var data=line.split(","); var row=sheet.getRow(r); line.split(",").forEach((d,i)=>{ row.getCell(i+1).value=d; }) r++; }).on ("end", function (){ var newFile= clean.replace("txt","xlsx"); workbook.xlsx.writeFile(newFile).then(function(){ console.log(newFile + " written"); }); }).read(); } }) } }) }) However i run out of java memory. The .txt files are 10Mb. I tried to increase it with --max-old-space-size, but it's still not enough. Any solutions ?

Submitted January 23, 2020 at 12:02PM by FireZura

Ecommerce platform recommendations

Does anybody have any recommendations for Node-based ecommerce platforms?Open-source or otherwise?

Submitted January 23, 2020 at 11:50AM by dynjo

Playing audio notifications in a Progressive Web App with a background process

Is it possible to have a progressive web app running in the background when a device is locked or the app is not open?Is it also possible for this background process to pause the audio and play it's own audio for a couple of seconds before resuming?

Submitted January 23, 2020 at 09:04AM by Administrator101

Mini Video Encoder implementation part 1

https://medium.com//mini-video-encoder-implementation-part-1-1fce5fb081c1?source=friends_link&sk=72073007e1ff7dac301de404cae57fc7

Submitted January 23, 2020 at 09:31AM by Fewthp

Issues with nodejs crypto (.NET 3DES Encrypt/Decrypt)

Hi r/node,I'm really stuck with converting a code to integrate with a .NET legacy code. I've tried a lot of libraries, such as crypto-js, crypto-es, but could not make this work.The original code that I need to integrate with is the following, and the tries I've made are in the bottom. If anyone have any idea of what mistakes I'm doing, could give me some insights?string passPhrase = "test0001"; // get the md5 hash of passPhrase as byte array byte[] md5PassPhraseHash = null; MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); md5PassPhraseHash = md5.ComputeHash(Encoding.UTF8.GetBytes(passPhrase)); byte[] decodedSecret = Convert.FromBase64String(secretAsBase64); TripleDESCryptoServiceProvider tdes_dec = new TripleDESCryptoServiceProvider(); tdes_dec.Key = md5PassPhraseHash; byte[] cIV_dec = new byte[8]; Array.Copy(md5PassPhraseHash, cIV_dec, 8); tdes_dec.IV = cIV_dec; MemoryStream memstream_dec = new MemoryStream(); CryptoStream cs_dec = new CryptoStream(memstream_dec, tdes_dec.CreateDecryptor(), CryptoStreamMode.Write); cs_dec.Write(decodedSecret, 0, decodedSecret.Length); cs_dec.FlushFinalBlock(); cs_dec.Close(); byte[] decryptedSecret = memstream_dec.ToArray(); Int64 secret = Convert.ToInt64(Encoding.UTF8.GetString(decryptedSecret)); // increment secret secret = secret + 1; byte[] encodedSecret = Encoding.UTF8.GetBytes(Convert.ToString(secret)); TripleDESCryptoServiceProvider tdes_enc = new TripleDESCryptoServiceProvider(); tdes_enc.Key = md5PassPhraseHash; byte[] cIV_enc = new byte[8]; Array.Copy(md5PassPhraseHash, cIV_enc, 8); tdes_enc.IV = cIV_enc; MemoryStream memstream = new MemoryStream(); CryptoStream cs = new CryptoStream(memstream, tdes_enc.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(encodedSecret, 0, encodedSecret.Length); cs.FlushFinalBlock(); cs.Close(); byte[] encryptedSecret = memstream.ToArray(); string secret_encrypted = Convert.ToBase64String(encryptedSecret); I've tried a lot of libraries and the native "crypto" package, but could not make it work. Can someone help me? Either I get invalid key length or even iv length issues.​Here's one of the tries:static decrypt(passPhrase: string, secret: string): string { const md5PassPhraseHash = crypto .createHash('md5') .update(passPhrase) .digest(); const decodedSecret = Buffer.from(secret, 'base64').toString(); const iv = Buffer.from(md5PassPhraseHash.slice(0, 8)); const decipher = crypto.createDecipheriv('des-ede3-cbc', md5PassPhraseHash, iv); decipher.update(decodedSecret, 'base64', 'utf8'); const result = decipher.final('utf-8'); console.log({ result }); return result.toString(); }

Submitted January 23, 2020 at 09:31AM by dtiziani