Saturday 29 February 2020

Beware of Pirple.com

So I subscribed to there membership account for about 2 months and I'm extremely underwhelmed. Its at best just another a udemy course but its actually way worse because there is no Q&A section or anything of help except their facebook group that is kind dead, oh and NO CUSTOMER SUPPORT at all.I had an issue with their SaaS program emails not working and the support ticket they sent says they'll reach out in 1 business day but if you're a premium member (which I was) they you can message directly on Facebook for faster response.I send multiple messages over the course of 4 days. I posted to their wall and the Admin didn't approve it (but approved other posts around the same time) so I know he saw it.So after 7 business days I canceled my subscription and just can't believe they are in business. Other teachers on Youtube and Udemy do a better job or at worse equal job to these idiots and they actually help students.judging by the facebook student forum they have its nearly all middle-east/Asian subscribers who sadly don't know better and are getting taken advantage of.I cannot stress enough how much everyone should stay away from Pirple

Submitted March 01, 2020 at 04:12AM by TheWrongDamnWolf

Secure Password Hashing with Argon2 and Node

https://youtu.be/Nyq4tqDNpnc

Submitted March 01, 2020 at 03:31AM by MuttyFTW

How To Use NodeJS Scraping to Read the New York Times for Free

https://fidget.dev/posts/read-the-new-york-times-for-free-using-nodejs-scraper/

Submitted March 01, 2020 at 01:56AM by blixxurd

multer and size of text area

I originally made a form that has a text area that has large quantities of text. This would be stored in database, and to get it working, I had to addapp.use(bodyParser.json({ parameterLimit: 10000000, limit: '50mb', type: 'application/json' })) app.use(bodyParser.urlencoded({ parameterLimit: 10000000, extended: true, limit: '50mb' })) but then I added image upload so I had to switch to multer. now multer seems to break when ever I fill the text box as intended. if I type something short into a text area, it works fine, but when full content is added, it behaves as if the field is empty, and since the field is required, it breaks down everything. Is there something that should be added to multer options, or somewhere else, to allow these extra large text fields?

Submitted February 29, 2020 at 11:57PM by wywrd

Code Review

Hello all!I am working on an open source project for gaming communities to be able to manage reports and bans.Currently it utilizes steam for authentication via passport-steam.This is my first coding project as a whole and I would love some critiques / security reviews on my work. You can find the project here

Submitted March 01, 2020 at 12:04AM by Deadlydragon218

Create a server for crossplattform communication with MongoDB

Currently I am working on a project where you can make notes and save them to an online account.As far as I know it is not recommended to let the user directly connect and manipulate a database. As a result I would have to write a server, the client connects to the server and the server makes the database lookups and returns the information. Is it intelligent to do this with node and return JSON files? Or are there other recommended, better, languages to do stuff like this.I would need somewhat of a login system and stuff like passport won't work when I try to connect the server from a language like C# or Java, is this correct?

Submitted February 29, 2020 at 09:41PM by hertelukas

Trying to make a discord bot which can visualize data

/r/learnjavascript/comments/fbhv9j/trying_to_make_a_discord_bot_which_can_visualize/

Submitted February 29, 2020 at 07:56PM by Kurohagane

setInterval does not trigger when the os sleeps (electron app)

I am implementing an app using ElectronJs where some subscriptions rely on timers. So, when I use setInterval to trigger a function at a given interval, this does not work if the system is went into sleeping mode during the interval.Is there a way to make it run even while the system is sleeping? Or if this is not possible, is there an alternative to setInterval?

Submitted February 29, 2020 at 06:57PM by oneevening

Today I published github-superfilter, a tiny web extension that helps you review pull requests, built with Node/TypeScript

GitHub Superfilter is a tiny web extension that adds a lovely filter to GitHub pull requests. It lets you search or filter files in a pull request and offers a bit more flexibility than the default GitHub filter. For example, you can search for a specific folder (/components/) or filter out specific extensions (!.test.js). It looks like this.Get it on Firefox or Google Chrome, or check it out on GitHub.You can use the codebase as boilerplate to build your own extension! If you were ever curious about creating web extensions, check out the code and modify it to fit your needs. The development and build flows are documented in the readme, so you can be up and running with your own extension in 5 minutes.Thanks for checking it out, and please let me know if you have any feedback.

Submitted February 29, 2020 at 04:47PM by TomerCodes

A Practical Introduction to GeoJSON with Node.js

http://thecodebarbarian.com/a-practical-introduction-to-geojson-with-node-js.html

Submitted February 29, 2020 at 04:45PM by pmz

What's the best way to go for making to seperate codes work together?

I have written two pieces of code. The first one is fetching newly added products on a website using puppeteer and writes the URL's as a text file in a designated folder using fs. The second code goes to the product page and fetches information as: price, name , product info etc. Whats the best way to make product fetcher use the URL's written by the first piece of code, and fetch the product info?

Submitted February 29, 2020 at 03:57PM by ludwigsterner

Is there some 'gotchas' when doing multiple mongodb $unsets? I can't get all my fields to be deleted.

When I run the following code I'm able to have field1, field4, and field5 get removed correctly. But fields 2 and 3 don't get deleted from mongo and it's driving me crazy.It'd make sense if the first was deleted but not the rest, but to have two fields in the middle never get removed is baffling.This is literally all there is to it:const query = { $unset : [ 'field1', 'field2', 'field3', 'field4', 'field5'], $set: {'boolval1': false, 'boolval2': false, 'boolval3': false } } Device.findOneAndUpdate({'id': deviceId}, query) The resolve comes back with the document the way I want it except that field2 and field3 still exist. I've checked the spelling multiple times and have even copied/pasted.Anyone come across something like this before?

Submitted February 29, 2020 at 04:15PM by 6ThePrisoner

Node webserver that shows a gui?

Angular 2 from React?

I made a very small Angular project a long time ago for school, and I've pretty much only been using the MERN stack for months now, but I just realized I've never made a full MEAN stack application, I'm getting a bit annoyed of React and want to really dive into Angular for once, how much different is it compared to React? I don't remember it much at all.

Submitted February 29, 2020 at 12:50PM by Haunt626

Testing Node serverless applications — AWS Lambda functions

https://blog.logrocket.com/testing-node-serverless-applications-aws-lambda-functions/

Submitted February 29, 2020 at 09:12AM by r-wabbit

Geo coding server-side

https://medium.com/javascript-in-plain-english/an-introduction-to-geocoding-using-node-js-fe1a5d3aa05c

Submitted February 29, 2020 at 08:11AM by Well_Gravity

Friday 28 February 2020

I created a library interacting with Google Drive. It can query, create/download file, create folder, etc..

https://www.npmjs.com/package/ts-google-driveHere are some code snippets```typescriptimport {TsGooleDrive} from "ts-google-drive";const tsGoogleDrive = new TsGooleDrive({keyFilename: "serviceAccount.json"});async function getSingleFile() { const fileId = ""; const file = await tsGoogleDrive.getFile(fileId); const isFolder = file.isFolder; }async function listFolders() { const folderId = ""; const folders = await tsGoogleDrive .query() .setFolderOnly() .inFolder(folderId) .run(); }async function createFolder() { const folderId = ""; const newFolder = await tsGoogleDrive.createFolder({ name: "testing", parent: folderId, });// try to search for it again const foundFolder = await tsGoogleDrive .query() .setFolderOnly() .setModifiedTime("=", newFolder.modifiedAt) .runOnce(); }async function uploadFile() { const folderId = ""; const filename = "./icon.png"; const buffer = fs.readFileSync(filename); const newFile = await tsGoogleDrive.upload(filename, {parent: folderId}); const downloadBuffer = await newFile.download(); }async function search() { const folderId = ""; const query = await tsGoogleDrive .query() .setFolderOnly() .inFolder(folderId) .setPageSize(3) .setOrderBy("name") .setNameContains("New");while (query.hasNextPage()) { const folders = await query.run(); for (const folder of folders) { await folder.delete(); } } }async function emptyTrash() { const trashedFiles = await tsGoogleDrive .query() .inTrash() .run();await tsGoogleDrive.emptyTrash(); }```

Submitted February 29, 2020 at 02:10AM by plk83

coding twitch bots

Hey , i know its out of topic but is it possible like for example I have 20 twitch accounts right? And is it possible to code so all of the accounts watch a specific twitch stream when the stream starts automatically And if its possible , is it possible to make them active 24/7? Ik it sounds kinda shady (wtf who says shady) but its not for a bad purpose its for an experiment and a youtube video

Submitted February 29, 2020 at 01:02AM by bs0202

Workspaces CLI - A small command-line tool to easily list and open your VS Code Workspaces written in node

https://github.com/woudsma/workspaces-cli

Submitted February 28, 2020 at 11:40PM by skatingteam

Get the standard music player

Is there any way to get the standard music player with Node.js (preferably cross-plattform) e.g. on windows you can choose to always open mp3 file with VLC, is there any way to get this setting? TIA.

Submitted February 28, 2020 at 11:46PM by dckjnls

node.js app and firebase auth issue (method not allowed)

My question: because this app I cloned is two years old. Is it likely to be a matter of syntax given more recent versions of Angular and Firebase ( e.g., the method name firebase.auth is now firebase.auth() )Context:Stack: Angular/Bower/Grunt/node.js + Firebase DB1.cloned prod app to a copy/dev instance - can't auth to new dev firebase DB. error:"firebase.auth is not a function at angularfire.js:43"angularfile.js is in the /app/src/bower_components directoryVerified appropriate API keys and unique identifiers were ported over to reflect the new instance's variables such as name, Firebase URL, etc.Forgive me, I am not a developer but do appreciate any pointers or reference material outside the official Google quickstart guide (it implies a brand new project which mine is not).

Submitted February 28, 2020 at 10:24PM by shermski4

Going to do a talk about the fs module in NodeJs in a few days

Alright so I need the attention of newbies and experts alike, I'm going to be giving out a talk to a whole bunch of teenagers who code, there'll be a few experts/people with professional experience too.I want to hear what kinds of things as a newbie you struggled to understand, would love more indepth knowledge in or needed some tips for.From experts, I want to know something that will be interesting to hear about, so that the experienced guys dont just yawn their way out of the session. Preferably within the context of fs.I've already established that I'll talk about fs.createReadStream and fs.createWriteStream and give an introduction to streams before because I personally struggled to understand them. Other than the usual stuff like introductions to nodejs, fs etc. etc. what can I talk about?Nervous as hell, need this a lot! Thanks a lot guys

Submitted February 28, 2020 at 10:48PM by HIV_isAProtein

Graph #1 | Data Structures in JavaScript | Top Tutorial & Implementation

https://youtu.be/-TLWEy6nGog

Submitted February 28, 2020 at 11:12PM by SynthesizeMeSun

A dashboard GUI and API to share services.

https://www.repoflow.com/blog/tunnels-tool/eWRhpR1.html

Submitted February 28, 2020 at 09:44PM by vicjicama

What's the best way to go about saving private keys in a production app?

So in every codebase there are a few private keys for different APIs and purposes (like for checking JWT signs). in a backend codebase on which 10 people are working there is this chance that someone let out the private key to some external hacker. what's the current best practice to avoid such vulnerabilities?

Submitted February 28, 2020 at 09:44PM by fiveMop

Getting connection timeout and ETIMEOUT errors with nodemailer to gmail with OAuth

I am getting ”Error: connect ETIMEOUT” and ”Error: Connection timed out” errors when sending email with gmail on nodemailer. My settings are fine with gmail OAuth, and ive used this setup before, and it has worked great, I havent changed anything. I have the client id and the client secret and refresh token. My target address for it is smtp.gmail.com, and the secure option is enabled and the port is 465, and pooling is enabled to 5 connections.Now all of the sudden im getting these errors. Ive literally changed nothing. And the funny thing is, ive been getting these errors for the past week AND NO EMAILS HAVE BEEN SENT SUCCESSFULLY, and now IVE CHANGED NOTHING! And its suddenly working again. If working counts as only 1/10 of emails fail.Ive not used my OAuth api that I use with the gmail setup of nodemailer basically not much at all, and ive enabled the highest free limits, and I also have GSuite on that account, which might also be making my API limits bigger. Ive sent literally like probably/tried to send around 140 emails a week, tops. The api limit is 2000 a day from what I remember. Its clearly not that.What the heck is the problem? It seems seemingly random, this happens with both smtp.googlemail.com and smtp.gmail.com. My pings to the addresses work fine. It does seem like a rate limit, but thats impossible, because there shouldnt be any rate limit like that.Has anyone had this issue? I have no idea what to do about it. I have firewalls yes, but they shouldnt be causing this, ive checked many times, AND IF THE FIREWALLS WHERE CAUSING THIS, theyd be blocking everyrhing! It would never work!Thanks in advance for any help.

Submitted February 28, 2020 at 08:30PM by livinglibary

Does anyone know why the subtract method in Moment.js doesn't accept variables?

I have a for loop where I need to generate different dates and then look up data according to the dates: for (let j = 7; j > 0; j--) { let beginningOfDay = moment().startOf('day').subtract(j, 'days').toDate() let endOfDay = moment().endOf('day').subtract(j, 'days').toDate() console.log(j) console.log(beginningOfDay) When I run the code, with this block in it, my log statements show descending integers for the value of j, but the the beginningOfDay log is blank. This only happens when I use j as the 'amount' argument in the subtraction method. If I replace 'j' with '3', it works just fine.Why is that?

Submitted February 28, 2020 at 07:13PM by Briyo2289

Did mongoose create users when I created a new tour schema or when I posted a user to it? Or am I wrong on both?

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

Submitted February 28, 2020 at 03:28PM by flat_soda_club

node-rsa error: incorrect data or key

I have the code :const net = require('net')const NodeRSA = require('node-rsa')​const key = new NodeRSA({b: 512})const key2 = new NodeRSA({b: 512})key2.setOptions({encryptionScheme: 'pkcs1'});key.setOptions({encryptionScheme: 'pkcs1'});​const server = net.createServer(socket => {socket.on("data", data => {key.importKey({n: Buffer.from(data, 'hex'),e: 65537,}, 'components-public');socket.write(key.encrypt(data, 'base64'))console.log("recieved key:", data);})socket.on("error", (err) => {console.log(err.stack)})})server.listen(8080)​const client = new net.Socket()client.connect(8080, "localhost", () => {client.write(key2.exportKey('components-public').n)console.log("sent key:", key2.exportKey('components-public').n);})client.on("data", data => {console.log(key2.decrypt(data, "utf8"));})However when I run this program I get the error:Error: Error during decryption (probably incorrect key). Original error: Error: Incorrect data or keyI assume I'm doing something wrong but I can't figure out what. Does anyone see what my problem is?

Submitted February 28, 2020 at 02:44PM by Totally_Oztralian

Is there any intelligent way to handle pathing/routing across folders?

So I'm learning node and making a website and I decided on a different folderstructure than express makes. I instead went the "folder per component/domain" type of setup.But that means that instead of having a routes folder with various subfolders I have a routefile+pug etc in its own domain/component specific folder and it gets really old fiddling around with '../../views/layout' type of pathing. Is there any good solution for that? Also any good solution for the same with routes and nesting routes (ie users/api users/api/sub1 users/api/sub2 etc)?thanks and have a great weekend!

Submitted February 28, 2020 at 01:03PM by Kukibur

ASK: How to build a simple runnable online editor?

Hi there,I am building an app that connects different data sources. I want to send data from one data source to another through API. But before I send it, I want to allow people to write a simple JS function that takes the data into that function and make changes and return a new/updated message. And this updated message will then be send to the other data source.So imagine I have a simple text area or a code-editor in my app and users will be able to write something like this where we are adding a property 'time'.function updateData(data) {data.time = new Date();return data;}​I want people to be able to 'deploy' this function and then test it. online live just like online editors do these days. How can I take the code in my code-editor in the front-end and deploy it and run it? Any pointers would be really appreciated!

Submitted February 28, 2020 at 01:04PM by rdv100

Which frameworks do I need to use to code this kind of website?

Hello friends. I have this wordpress theme but it is not reliable, not stable, wordpress slow and buggy. It has great features though. I want to code it from scratch. What I need is a directory theme basically. There is an openstretmap, places and restaurant on the map. When I click to the place go to its own page with menu, business hours etc. Also I need to ask permission for location and show the places around them. Which frameworks and technologies do I need a stable, fast website with admin panel? Node.js? Express? Thank you.

Submitted February 28, 2020 at 10:51AM by steppenwuf

Can someone please help? Making a call to an ExpressJS route, and need to do a GET request to an API in it

/r/learnjavascript/comments/fariwn/node_making_a_call_to_an_expressjs_route_and_need/

Submitted February 28, 2020 at 08:16AM by ThunderBow98

Thursday 27 February 2020

How I built the "Quora for Coders" using NextJS

https://www.codequery.io

Submitted February 28, 2020 at 05:20AM by stackchief

NodeJS+Express+MySQL+Socket.io API design

Hello all. I've delved into the world of opensource ecosystems in the past 9 months after 15 years away from tech ... wow things have changed since the days of JS in the early 2000's :SI've built a project using NodeJS+Express+MySQL with a HTTP request API, and now that i've gotten up to speed with JS etc. i've decided to move into react. Fortunately this is giving me the opportunity to rewrite my project from the top down, and I can right all the horrendous wrongs of my first projects 'learning phase'.The project can roughly be described as:-A web scraping service that harvests data from many different public facing sources on the WWW, incl. puppeteer driven web scraping, tapping into public APIs, etc.This service then feeds all the data into a MySQL database. The scraping service is rock solid, and has collected 5 million rows of data already and is working well with no issues. The DB itself could do with some optimizations, but the query with the highest cost returns the data in < 2 seconds so i'm not too worried.In the first iteration of my project, i created an API, which while rough and designed as i went, served it's purpose and did it well. However now that i am onto the re-write, i wanted to seek advice on design ideas around an API such as this.There was a single API endpoint, but i would create a view in MySQL for each different data set i wanted to be able to access. It wasn't a completely open conduit to the database, as the requested view had to be in a list that was checked, so accessing anything other than what i allowed was not possible.This also allowed me to use the view to transform the data, and the API code simply had to parse it into JSON and return it. This left the GROUP, ORDER, JOIN, etc. logic out of Node and in SQL where, in my view, it should be.The data from this API would be used to populate charts, and the front-end would just poll the API every 10 minutes, 30 minutes, or whatever, and update the chart ... Works well but i feel that there must be a better way.I guess my thoughts are primarily around whether using SQL views in this way has any downsides or hidden flaws. An immediate one i have come into is that using something like mysql-events in Node can track changed to BASE TABLES, but i'd need to write additional logic/mappings to establish which views are affected, what data is new, etc. etc.If i fed data from table to Node API server, the mysql-events could essentially just stream changes to the API (or another service), which could then be pushed via socket.io to subscribed clients.any ideas or recommendations? I prefer to keep things simple and dynamic as the project is very much a evolving design. I've had many years of programming experience in Pascal, PHP, SQL, JS, HTML, etc. but i have never working as a coder professionally, and this tends to make me feel that i deviate far from best practise sometimes.The API's only requirement is that it serves time-series data to the front-end, and keeps them updated when new data is brought in... Timeliness is not critical, but always welcome.The project does have a commercial sensitivity so i am reluctant to post the link on here, but i will be happy to provide it to those who want to contact me directly.I hope this makes sense... I started rambling :S

Submitted February 28, 2020 at 04:08AM by the-retlif

CORS sans ExpressJS

Working on a project here... - backend: node + mongo - front end: react app via create-react-appRunning into CORS issues making requests from the front end. In the pat I’d install the CORS module, set it up and move on but I’m not using Express and every mention online of the CORS module mentions Express as well.Wondering how some of you might handle this?

Submitted February 28, 2020 at 03:21AM by yrevapop

Port sharing with SNI?

Is it possible to run two instances of NodeJS on the same box, using the same TLS port 443, but responding to different DNS names via Server Name Indication (SNI)? I'm just learning Node and I've used this technique in the past with other web servers. Would this have to be handled via something like nginx instead?

Submitted February 28, 2020 at 12:27AM by Xaxoxth

Five Misconceptions on How NodeJS Works

https://blog.insiderattack.net/five-misconceptions-on-how-nodejs-works-edfb56f7b3a6

Submitted February 28, 2020 at 12:03AM by dpjayasekara

Rest api to compare data from database against each other

I want to create a simple REST API that works with data that is stored in a database like mysql. The schema of the database looks some thing like this:wrestlers:“id”: 1,“name”: “batista”,“signature move”: “batista bomb”,“powerlevel”: 5, “deactivated”: false,Alltogether there are 15 wrestlers with signatures moves and powermoves. I want to split the wrestlers into groups of 5 and each group will fight against a wrestler of another group and there can be only one winner. These should lead to 5 fights in total. The winner is determined by the powerlevel of each wrestler. so if wrestler 1 has a greater powerlevel than wrestler 2 then wrestler 1 wins. If deactivated is true then the other wrestler wins automatically if the deactivated is false. I don't want a solution. I just want an Idea on how to implent this. Could someone give me an Idea. Thank you in advance.

Submitted February 27, 2020 at 09:46PM by roronoajoyboy

How to secure an at home Ubuntu Node Server?

So currently I have a server running, it uses mongoDB as its database, and also stores files inside of it (using gridFS). All files are first encrypted by a global server password (it acquires this key as the server first starts up.), I chose not to use each users password to encrypt the data because I was worried someone could just look at the mongoDB database (if they had physical access), and just take the passwords from there, I did not want to store the encryption password anywhere on the server. And also I would run into complications when a user wanted to change their password (would I reencrypt every single chunk of that user? Or perhaps still store the old password?).But, what would stop someone from just using the mongoDB CLI tool (again assuming they have physical access), and just change a users password while its still running (so they do not lose that encryption key on startup), log into their account, and finally download their data?I looked into adding authorization to mongoDB, but it seems like there is still always an admin account active, no matter what, if i'm not mistaking. Is there any way to make it so only node can access mongoDB after some type of authorization? Or perhaps lock the Ubuntu system so if someone did have physical access they couldn't just run commands, and snoop around the database?Sorry this might not be the best sub to post this, please let me know if there is a better one.

Submitted February 27, 2020 at 09:05PM by subnub99

How to omit a key inside array of objects?

For example if I have a JSON like this :var a = {'name' : 'OBJ NAME','place' : {'location' : UK},layout : [{id : 1, name : 'ONE'},{id : 2, name : 'TWO'},{id : 3, name : 'THREE'}]}Now if I want to omit id from layout array, how do I do this?I know that by _.omit(a, ['place.location']) can be used to omit nested properties but I don't know how to do this on an array. Is there any way to do this?

Submitted February 27, 2020 at 06:20PM by GhostFoxGod

What are some libraries to learn after you are comfortable with Node and what are they used for?

I’m starting to get my foot in the door and wondering where to go next? Thanks !

Submitted February 27, 2020 at 06:26PM by flat_soda_club

With node child_process, how to open cmd prompt as admin in windows.

Use case : want to change system time from code.

Submitted February 27, 2020 at 05:09PM by VINNU_THE_UNIQUE

DiscordJS can't read the channel name from a function

/r/Discordjs/comments/faf57v/discordjs_cant_read_the_channel_name_from_a/

Submitted February 27, 2020 at 05:08PM by Shy_Cryptic

Curveball - a modern typescript microframework, with built-in support for AWS Lambda

https://evertpot.com/curveball-typescript-framework-update/

Submitted February 27, 2020 at 04:48PM by evert

Can anyone suggest how to get single executable from node js project .

No text found

Submitted February 27, 2020 at 04:16PM by VINNU_THE_UNIQUE

How do I make my own router?

https://gist.github.com/kkamkou/4348680I'm studying middleware, trying to make my own router(for a json restapi only). Using this as a reference.My question is: how do you make sure that requests and responses don't get confused?Scenario: App makes a get request, then it makes another one before it got the response from the first one. How do I make sure they return in the correct order?

Submitted February 27, 2020 at 12:22PM by MelkorHatedValinor

Add Team members in SaaS?

What library/framework/architecture do you use to give users of a SaaS to add their team members and share the plan?

Submitted February 27, 2020 at 11:29AM by sushantshekhar20

How to pass byte[] type variables to FFI imported DLL in nodeJS?

(xposted on StackOverFlow)Below is an excerpt csharp implementation of Wireguard client using the DLL. (https://github.com/WireGuard/wireguard-windows/tree/master/embeddable-dll-service)```csharp /* SPDX-License-Identifier: MIT * * Copyright (C) 2019 WireGuard LLC. All Rights Reserved. */using System; using System.Runtime.InteropServices;namespace Tunnel { public class Keypair { public readonly string Public; public readonly string Private; private Keypair(string pub, string priv) { Public = pub; Private = priv; } [DllImport("tunnel.dll", EntryPoint = "WireGuardGenerateKeypair", CallingConvention = CallingConvention.Cdecl)] private static extern bool WireGuardGenerateKeypair(byte[] publicKey, byte[] privateKey); public static Keypair Generate() { var publicKey = new byte[32]; var privateKey = new byte[32]; WireGuardGenerateKeypair(publicKey, privateKey); return new Keypair(Convert.ToBase64String(publicKey), Convert.ToBase64String(privateKey)); } } } ```Now I want to port this code to nodejs using the same DLL. I came so far from this sample project.```nodejs /* Node 10 and lower npm i ffi https://www.npmjs.com/package/ffi https://github.com/node-ffi/node-ffi Node 11 and higher npm i @saleae/ffi https://www.npmjs.com/package/@saleae/ffi https://github.com/lxe/node-ffi/tree/node-12 */// Import dependencies const ffi = require("@saleae/ffi");var ref = require('ref');// Convert JSString to CString function TEXT(text) { return Buffer.from(${text}\0, "ucs2"); }// Import tunnel const tunnel = new ffi.Library("wireguardfiles/tunnel", { "WireGuardGenerateKeypair": [ "bool", ["String", "String"] ] });var publickey = "string"; var privatekey = "string";var result = tunnel.WireGuardGenerateKeypair(publickey, privatekey)process.stdout.write(result); ```As you can see it is clearly wrong since I am using String instead of byte[]. This is because I got TypeError: could not determine a proper "type" from: byte[] error.Any idea on how to pass byte[] arguments to DLL from nodejs?Thank you!

Submitted February 27, 2020 at 09:16AM by shiskeyoffles

Wednesday 26 February 2020

304 responses

I deployed my mern app to heroku and my api is returning 304 requests for some reason. Is this supposed to happen? shouldn't it be 200?I am still a newbie to programming. please help.

Submitted February 27, 2020 at 04:09AM by undo124455

Node vs Flask Benchmark

https://github.com/StackHack-Dev/benchmarks/blob/master/node-flask/result.md

Submitted February 27, 2020 at 03:32AM by pverma8172

mssql and GO calls

I have a .sql file that has stored procs in it and a couple 'GO' calls. I couldn't get my code to work with the GO calls. I changed them to ; and then I do a simple toString() and split(';') on the file and run the queries. it seems to be working... is that fine to do ? should this file be formatted in a particular way to work better with mssql ?

Submitted February 27, 2020 at 03:43AM by superfake123

MEAN Stack Angular 9 Build Realtime CRUD Web App Quickly

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

Submitted February 27, 2020 at 12:47AM by didinj

Can someone explain the node sessions to me?

Hi all! Probably a really dumb question.I don't have any expirience with server based application development, except for maybe some general things. Previously I worked with JS for about a year and a half.So we have this legacy system, which I used to receive and send http requests to via REST in JS. It only accepts basic HTTP auth and returns JWTs back to store in a cookie (I stored them in a global variables, yeah, I know) and make requests with. Since all JS is client-side and my apps never had to be bigger than one page I never had to bother with any kind of session control, as it was managed by the legacy system itself.I now have a goal of creating a server-side application. I understand the basic concepts of node, express, app structure, routing, exporting, static files, etc, but what about multiple users using my app?I played with express session and redis for a bit and was able to get it to work. What I have right now is a demo login page and a demo landing page. If user opens /login, a cookie is generated, then user "logs in" and their username is added to req.session.user, then I ask if (req.session.user === 'demo') and if it is, user is allowed to proceed to the landing page, and if not he is redirected back to login. Is this correct? I feel like it's not...Especially the req part. :(As of now I have the following ideas about the procedure I need:1) Serve static login page to user, on submit grab user and password values and send them to the legacy system via AJAX or http:2) Get a token back, store it in a res.cookie;3) Use it to make GET only request to the legacy system (for now);4) Get the JSON back, render it with handlebars (for ex) and... Then what? Will this part be managed automatically? Currently I have this thing where I can see previous user's Information when I log in. I don't exactly understand how does Express distinguish between users and what to serve to whom. If I get data from our system with JWT in a cookie will it be rendered differently for each user because of his individual session? I feel like a moron but I just can't wrap my head around it all. Please help!Thank you!

Submitted February 26, 2020 at 09:16PM by buttermatter92

Dates in MongoDB

I know this has been written about a lot, but I can't figure it out.I have a collection called "bracetimes" with a document, like this:_id: ObjectID(5e56cf9ae65bf2b30a6ab525) user_id: ObjectID(5e56bb2b40ad526200401773) start: 2020-02-26T00:00:00.000+00:00 // 12am stop: 2020-02-26T12:00:00.000+00:00 // noon The start and stop attributes are Date objects, ISOdate specifically (I thought that was the problem, but I'm not sure anymore).I have a search query that should find the above document, but does not: const startOfDay = moment().startOf('day').toISOString() const endOfDay = moment().endOf('day').toISOString() const currentTime = moment().toISOString() // search query { $and: [ { user_id: ObjectID(myUser._id) }, { $or: [ { $and: [{ start: { $gt: startOfDay } }, { start: { $lt: endOfDay } }] }, { $and: [{ stop: { $gt: startOfDay } }, { stop: { $lt: endOfDay } }] } ] } ] } Basically, I am looking for records that 1) match the right user_id and 2) have a start OR stop point between the startOfDay and endOfDay.I had essentially the same query working when the database was was holding unix integers, instead of dates (the moment constants were using .unix() instead of .toISOString() ), but now that I am trying to use dates I can't get it working.Any advice is much appreciated.

Submitted February 26, 2020 at 08:30PM by Briyo2289

How to make sure that the uploaded images are safe to send to my users

so i'm building a application where the users can upload a profile picture and this will be seen by the other users. So i dont want a image to contain anything malicious or anything like that. I have googled and looked at some videos, and the best i can find is that i should set a file limit and look at the bytes when the file is uploaded. But is there a method that is often used or is it best to just remove this future.

Submitted February 26, 2020 at 08:01PM by Flurgi

Can someone explain to me how Electron exports itself?

Probably a noob question. In node_modules/electron/index.js ( screenshot ), how does Electron export its modules? From what I can tell, it's just exporting a string.How can const {dialog} = require('electron') work if all it exports is a string?

Submitted February 26, 2020 at 07:28PM by abandonplanetearth

When Should You Use MongoDB Indexes?

http://thecodebarbarian.com/when-should-you-use-mongodb-indexes.html

Submitted February 26, 2020 at 04:39PM by code_barbarian

Blockchain NodeJs

I would love to know what are some useful tips on learning writing Node APIs for blockchain? tutorials or blog post will be greatly appreciated.

Submitted February 26, 2020 at 04:45PM by geek_guy1

What are the restrictions from the WASM "sandbox" in Node?

The Node API docs for WASI say:WASI gives sandboxed WebAssembly applications access to the underlying operating system via a collection of POSIX-like functionsBut I can't find information anywhere on exactly what the "sandbox" isMy understanding is that the WASM script has no access to memory outside of it's sandbox. Is that a good assumption?I would guess that the constructor arguments (args and envs) are copies of the corresponding data structures (process.argv and process.env) in the Node script environment?Does the WASM script have any access to system resources - IPC sockets, network, file system, or any other system call?

Submitted February 26, 2020 at 04:16PM by calligraphic-io

Accepting newbie questions here?

Didn't notice any sub rules but noticed the questions and dialogue are pretty advanced.Is this sub open to beginner questions?

Submitted February 26, 2020 at 03:41PM by shermski4

Adding Login to Vue.js bootstrap template

I have created a login using Twitter authentication through Vue, VueX and Firebase. This is the code: https://github.com/RyanMurph17/Login.However, I want to incorporate the login to my other dashboard application as it has a nice bootstrap template ( https://github.com/RyanMurph17/Dashboard ).I want the user to sign in and be directed to 'UserProfile.vue' (stats) rather than 'Home.vue'. This may be a simple routing issue but the main.js and routing differs from the login. My efforts have failed thus fair. The code from Login has been transferred over to Dashboard. I have scrapped the Navguard component and it may conflict.Any someone please help me out?​https://preview.redd.it/igc2nh7ziaj41.png?width=2235&format=png&auto=webp&s=eb4a14cbd1bb7bf5dbc72431783a6b7d5b0c8de2

Submitted February 26, 2020 at 03:58PM by RyboXBL

Using Node.js to clear files with admin (or current user permissions)?

I am currently working on an application in Electron that is designed for essentially running day-to-day operations for my users and as part of that I need to have options that users can click on to clean up files.A user can delete these files normally and I have the function that will delete the file in the folder however the issue comes up that there is insignificant privileges for my application to delete these files.Below is my code I'm currently using that would just clean up the users temp folder.function runMaintenance(app) { console.log(process.env.TEMP) if (app == 'app-main1') { const dir = process.env.TEMP; fs.readdir(dir, (err, files) => { if (err) throw err; for (const file of files) { fs.unlink(path.join(dir, file), err => { if (err) throw err; }); } }); }; }; fs and path are declared in my main.js file.I am not sure if there is a way to delete these files using the permissions of the current user or as admin.Is there any known way to do this?

Submitted February 26, 2020 at 02:17PM by akblais

Microservices interview questions?

Recently, a friend of mine (from a software company that I work in) noticed that more and more people are searching online for interview questions related to microservices. Well no wonder, captain obvious - this topic is now extremely popular.We’ve talked about it a bit and he admitted that he’s also asking microservice-related questions during job interviews (he’s the head of Node.js development in our company). Eventually, he decided to write an article about it to help the candidates: https://tsh.io/blog/microservices-interview-questions/The article is already online but I thought (kinda behind his back xD) that I’d consult it with you, the good people of r/node.Do you have similar experiences? Were you questioned about microservices during your recent job interviews? Do you think that microservices architecture know-how is important for every Node developer? Or maybe only the chosen ones?

Submitted February 26, 2020 at 02:27PM by placek3000

What would be the best approach for multi-user voice chat?

Hello!So I am currently in the plans for a fun little project, I want to have a NodeJS server running that people from a regular browser can connect to (around 5+ people) and hear each other.I have been looking at PeerJS but that seems to only be working for person to person communication, is there any other library I could use that might work?

Submitted February 26, 2020 at 12:41PM by TheRavenBlue

Weird error (segmentation fault )

I am working on a project that require node 8.x.x, but now I globally installed node 12.x.x, so I yarn add n (node version management tool). And using that tool to install node 8.x.x, but in the middle of installing I have:``` installing : node-v8.12.0mkdir : /usr/local/n/versions/node/8.12.0fetch : https://nodejs.org/dist/v8.12.0/node-v8.12.0-darwin-x64.tar.xz###################### 31.1%curl: (92) HTTP/2 stream 1 was not closed cleanly: INTERNAL_ERROR (err 2)bin/node: Lzma library error: No progress is possibleinstalled : (with npm ) ``` And then no matter what I entered like node -v npm -v gives me segmentation fault. I don't know how to handle this, what is going wrong?

Submitted February 26, 2020 at 12:12PM by GreatFireWallSucks

DDD in Node/Typescript, the functional way. Part 1

https://medium.com//ddd-in-node-typescript-the-functional-way-part-1-98d18d998b33?source=friends_link&sk=3ce0d45a14087eb4d2995e7f36f4b776

Submitted February 26, 2020 at 10:32AM by Fewthp

How do I implement a search function in my node.js web app?

Hi all, I recently startded using node and I'm making a simple web app for a boardgame with EJS templates (+bootstrap), every page is rendered from an .ejs template and is populated with data taken from .json database files (with game rules etc.).What I'd like to know is how do I "bind" a term to a page? If the user search for a specific rule, say "how to win", and my .json file contains the object with the how to win rule, how does the search engine know at wich URL that term can redirect? I know there are "indexes", but does this mean I have to "rewrite" my site in some other form with term -> url?In the end what is the way to add a search engine in node.js? where do I start?

Submitted February 26, 2020 at 09:29AM by Artemis_21

Authenticated API calls from a mobile app?

Hey guys, I was wondering what the industry standard for authenticating API calls via a mobile app is? I’ve used JWT before, if there is user login on the app and they stay logged in over a long period of tine, do i just keep refreshing the token?Any advice is welcome, thank you!

Submitted February 26, 2020 at 07:56AM by TheRealSteven

Tuesday 25 February 2020

Trying Lambda Functions with Puppeteer and getting Browser error

Hey, I wasn’t sure if this is related to Netlify or Puppeteer, but does someone know what’s causing the following error: Browser is not downloaded. Run "npm install" or "yarn install".It’s from a catch block in the the following codeconst chromium = require('chrome-aws-lambda'); const puppeteer = require('puppeteer-core'); exports.handler = async function (event, context, callback) { const molUrl = 'https://paikat.te-palvelut.fi/tpt/?searchPhrase=web%20developer&locations=Oulu&announced=0&leasing=0&english=false&sort=1'; let browser = null; let urls = null; try { // setup browser = await chromium.puppeteer.launch({ executablePath: await chromium.executablePath, args: chromium.args, headless: chromium.headless, //ignoreDefaultArgs: ['--disable-extensions'], defaultViewport: chromium.defaultViewport, }); // Do stuff with headless chrome const page = await browser.newPage(); await page.goto(molUrl); await page.waitForSelector('.resultsList a'); urls = await page.evaluate(() => { let results = []; let items = document.querySelectorAll('.resultsList a'); items.forEach((item) => { const itemShortUrlArray = /^.+[\?]/.exec(item.getAttribute('href')); const itemShortUrl = itemShortUrlArray[0].slice(0, -1); results.push({ url: itemShortUrl, text: item.innerText, }); }); return results; }); console.log('urls', {urls}); } catch (err) { console.error('Catch error:', err.message); } finally { if (browser !== null) { await browser.close() } } return { statusCode: 200, body: JSON.stringify({ urls: urls }) }; } Here’s the full local server log$ npm run lambda-serve > mol-job-search-automation@1.0.0 lambda-serve C:\xampp\htdocs\mol-job-search-automation > netlify-lambda serve functions netlify-lambda: Starting server Hash: e27c2e9de00b1c3503e6 Version: webpack 4.41.6 Time: 2550ms Built at: 2020-02-24 23:56:25 Asset Size Chunks Chunk Names scrapeMol.js 679 KiB 0 [emitted] scrapeMol Entrypoint scrapeMol = scrapeMol.js [0] external "fs" 42 bytes {0} [built] [1] external "path" 42 bytes {0} [built] [4] ../node_modules/puppeteer/lib/helper.js 8.62 KiB {0} [built] [5] ../node_modules/puppeteer-core/lib/helper.js 8.62 KiB {0} [built] [7] external "url" 42 bytes {0} [built] [13] external "https" 42 bytes {0} [built] [109] ../node_modules/puppeteer-core/index.js 1.5 KiB {0} [built] [111] ../node_modules/puppeteer-core/lib/Puppeteer.js 2.7 KiB {0} [built] [112] ./scrapeMol.js 1.57 KiB {0} [built] [113] ../node_modules/chrome-aws-lambda/source/index.js 5.91 KiB {0} [built] [114] ../node_modules/lambdafs/build/index.js 3.72 KiB {0} [built] [136] ../node_modules/chrome-aws-lambda/source/puppeteer/lib sync ^\.\/.*$ 226 bytes {0} [built] [155] ../node_modules/puppeteer/index.js 1.5 KiB {0} [optional] [built] [191] ../node_modules/puppeteer-core/lib/api.js 1.75 KiB {0} [built] [197] ../node_modules/puppeteer-core/package.json 3.34 KiB {0} [built] + 183 hidden modules WARNING in ../node_modules/lambdafs/build/index.js 23:31-46 Critical dependency: the request of a dependency is an expression @ ../node_modules/chrome-aws-lambda/source/index.js @ ./scrapeMol.js WARNING in ../node_modules/ws/lib/buffer-util.js Module not found: Error: Can't resolve 'bufferutil' in 'C:\xampp\htdocs\mol-job-search-automation\node_modules\ws\lib' @ ../node_modules/ws/lib/buffer-util.js @ ../node_modules/ws/lib/receiver.js @ ../node_modules/ws/index.js @ ../node_modules/puppeteer-core/lib/WebSocketTransport.js @ ../node_modules/puppeteer-core/lib/Launcher.js @ ../node_modules/puppeteer-core/lib/Puppeteer.js @ ../node_modules/puppeteer-core/index.js @ ./scrapeMol.js WARNING in ../node_modules/ws/lib/validation.js Module not found: Error: Can't resolve 'utf-8-validate' in 'C:\xampp\htdocs\mol-job-search-automation\node_modules\ws\lib' @ ../node_modules/ws/lib/validation.js @ ../node_modules/ws/lib/receiver.js @ ../node_modules/ws/index.js @ ../node_modules/puppeteer-core/lib/WebSocketTransport.js @ ../node_modules/puppeteer-core/lib/Launcher.js @ ../node_modules/puppeteer-core/lib/Puppeteer.js @ ../node_modules/puppeteer-core/index.js @ ./scrapeMol.js Lambda server is listening on 9000 Request from ::1: GET /scrapeMol.js Catch error: Browser is not downloaded. Run "npm install" or "yarn install" Response with status 200 in 246 ms. I’m not sure if the warning about the Critical dependency is anything to do with this. I’ve googled it and haven’t been able to figure out a fix for that either. Other things to note, I’m working locally (with netlify-lambda serve functions) on Windows.If anyone has any advice, I would really appreciate it.Thanks.

Submitted February 26, 2020 at 06:46AM by hey__its__me__

Express Circut Breaker - A solution for protecting certain parts of your express API from failing twice

https://www.npmjs.com/package/express-circut-breaker

Submitted February 26, 2020 at 05:30AM by danhab99

Express & MySQL tutorial for creating a CRUD (Create, Read, Update, Delete) App

Hi everyone,I created a tutorial showing how to create a fullstack web app using the express framework, MySQL, HTML, CSS, and JavaScript. For this app, we create have a simple input that lets you add names to a table.In that table we can edit the name or delete that row. We also implement a simple search feature.This is a simple app but it teaches the basics of connecting a backend (express in this case) to a MySQL database and the CRUD functionality.I hope this is a helpful tutorial.https://www.youtube.com/watch?v=vrj9AohVhPA

Submitted February 26, 2020 at 04:19AM by basketballcode23

Issue with CORS, domain, "No 'Access-Control-Allow-Origin' header is present on the requested resource."

Hi all, I have a Node/Express app deployed to Heroku. It works great there, however I bought a domain for it and when I try and access the application there I get a CORS issue.Access to XMLHttpRequest at 'https://myapp.herokuapp.com/getPosts' from origin 'https://myapp.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. However, I have CORS set up on my server.app.use(cors({ credentials: true, origin: ['https://myapp.app/', 'https://www.myapp.app/', 'http://localhost:3000'] })); Everything appears to be set up properly. Has anyone seen this issue before? Any help would be greatly appreciated. Thanks!

Submitted February 26, 2020 at 02:08AM by macswaggerrrr

When you import a database with mongoose in Node, can you import another one?

Im taking an online class and am confused on how the information is being posted/deleted/updated. I cannot find the trace in the code to see where it officially posts. I understand the create automatically calls the save feature, but am having a bit of a hard time wrapping my head around it. If anyone wants to call over discord so I can show you thatd be great. Its fairly simple since I am a beginner

Submitted February 25, 2020 at 08:47PM by flat_soda_club

Just started studying Node JS. I have a background in game development. Any advice to avoid the usual beginner mistakes? useful resources?

No text found

Submitted February 25, 2020 at 08:52PM by rosterbyte

Selection Sort | Full Algorithm Implementation in NodeJS | Love your feedback

https://youtu.be/t9_2LNFj3KE

Submitted February 25, 2020 at 06:42PM by SynthesizeMeSun

How about 'no'

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

Submitted February 25, 2020 at 06:43PM by lphartley

SchemaUI - Turn your mongoose schemas into a shiny CMS!

I would like to introduce to you, the latest open-source project I took part in the development, which will help you to turn every mongoose schema you already have into advanced CMS, with almost zero code.What's the big deal? Good question - by registering your schema, in case you set it properly with enums validation or custom validators, it will strict the forms with the setup you already did! i.e - a field with enum property will eventually be rendered into a dropdown field with limited options.The main purpose is to easily manage your DB, with friendly UI, and allow you to grant access for non-developers to work with the DB, without afraid that they will sabotage things :)Teaser from our huge backlog - Advanced dynamic filtering, Exporting data (csv/json), automatic audit log AOTB and much more.PRs are welcome, Bugs also. And of course - your feedback.SchemaUI package - https://www.npmjs.com/schemauiYou can also find a working live demo -> https://github.com/molaga/schemaui-demo

Submitted February 25, 2020 at 06:30PM by NesheR16

Five Myths used in “Golang vs Node.js” debate

http://ithare.com/five-myths-used-in-golang-vs-node-js-debate/

Submitted February 25, 2020 at 04:56PM by headevershaker

Puppeteer with an array? And stupid google login issue.

Hi everyone, I need some assistance. 2 questions that I will preface with I'm a SysAdmin not a coder, please be gentle :)​1) With the code below working to take screenshots using puppeteer, how can I loop thru the function as an array? I'm thinking it has to be synchronous due to the screenshots? I want the array list to pass the URL and filename.2) I need to take screenshots of some google analytic reports. Stupid chrome (and chromium) is giving me " Couldn't sign you in....This browser or app may not be secure. " Of course if I just run chrome I can login just fine, but not using this code. I've even tried changing the user agent. Has anyone worked around this issue?​const puppeteer = require('puppeteer')// I need to use the userDataDir to store session and cookies.const takeScreenshot = async (x,y) => {const browser = await puppeteer.launch({headless: false, args: ['--start-maximized', '--password-store=basic'], executablePath: 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',userDataDir: './userdata/Default3/'});​const page = await browser.newPage();const options = {path: 'images/image' + y + '.png'};​await page.setViewport({ width: 1920, height: 1080 });await page.goto(x);await new Promise(resolve => setTimeout(resolve, 5000));await page.screenshot(options);await browser.close();}​takeScreenshot('http://datastudio.google.com', 'google1');​// How do I do something like this?// let sitearray = [['https://www.cnn.com','testb1'], ['https://www.google.com','testb2'];// sudo code: for A in sitearray do takeScreenshot (sitearray[A.0],sitearray[A.1]) ??????????????

Submitted February 25, 2020 at 04:10PM by ImCaffeinated_Chris

Is here anybody who switched from PHP to node, why did you?

No text found

Submitted February 25, 2020 at 04:10PM by mostknowndeveloper

Beggar HTTP Client Close to V1.0.0

Hi, I posted last week about my new http client module Beggar for NodeJS.Since then I have been hard at work testing and writing features that I think the community might like.Beggar's API is mainly inspired by Mikael's request. I also need to mention SindreSorhus's Got for some features like Request Cancellation.At this point I am very close to releasing a v1.0.0 but before I do I hope to get back as much feedback as possible before I commit to no breaking changes.Here is a list of features that beggar supports:* Stream support (Duplex - reading from and writing to connection) * Promise support * Implicit parsing of response body (json, string, buffer) (possible to opt out) * form and multipart-form requests * Specify number of maximum redirections * Basic Auth * Automatic decompression of gzip, deflate and br compressions (possible to opt out) * Can reject non 2xx statusCode responses automatically * Proxy support for http proxies * Request Cancellation * Extending with user provided default optionsI am very interested in knowing what features may be missing and what kind of defaults you would prefer in a http client? For example currently the response will be resolved regardless of statusCode by default. Should the default be to reject on non 2XX statusCodes?Anyways thank you so much to anybody who takes the time to look at it, and to everybody who did so last time when I posted. Hopefully next time I post it will be to announce the v1.0.0 release!Beggar

Submitted February 25, 2020 at 02:00PM by davidmdm

Simple project to learn node

Write a simple project that I could be develop with node is for educational purpose pls

Submitted February 25, 2020 at 01:17PM by rifax99

Failed to load resource: the server responded with a status of 404 (Not Found)

What's your favorite ORM for postgreSQL?

What is your favorite Node.js ORM for postgreSQL?Is there anything out there that offers a similar experience to MongoDB and mongoose? That's what I'm most familiar with, but looking to jump into postgreSQL... hoping there is something out there to make my transition a little easier.

Submitted February 25, 2020 at 12:49PM by foundry41

Display API on Vue.js app

When i star my .bat file this happens: Error: Cannot find module ':/botconfig.json'

i'm trying to learn how to code a little discord bot​When i try to run the .bat file in cmd it shows an error i cant findCode:const botconfig = require(":/botconfig.json");const Dsicord = require("discord.js");const colours = require("./colours.json");const bot = new Discord.client({disablEveryone: true});bot.on("ready", async () => {console.log('${bot.user.username} is online')bot.user.setActivity("WhereToGo...", {type: "steaming"})})bot.on("message", async message => {if(message.author.bot || message.channel.type === "dm") return;let prefix = botconfig.prefix;let messageArray = message.content.split(" ")let cmd = messageArray[0];let args = messageArray.slice(1);if(cmd === '${prefix}play'){return message.channel.send("hello")}if(cmd === '${prefix}serverinfo'){let sEmbed = new discord.RichEmbed().setcolour(colours.yellow).setTitle("ServerInfo").setThumbnail (message.guild.iconURL).setDescription("USE ME SENPAI!").setAuther('${message.guild.name} Info', message.guild.iconURL).addFeild("**Guild Name:**", '${message.guild.name}', true).addFeild("**Guild owner:**", '${message.guild.owner}', true).addFeild("***Member Count**", '${message.guild.MemberCount}', true).addFeild("**Role Count**", '${message.guild.role.size}', true).setFooter('WhereToGo... | Footer', bot.user.displayAvatarURL)message.channel.send({embed: sEmbed});}})bot.login(botconfig.token);

Submitted February 25, 2020 at 11:52AM by TheThingIUsedToFuck

Any Node.js package that can parse a cookie that have multiple values on the same name?

Looks like the 3 top cookie libraries are not able to parse cookie that have duplicate namescookie https://github.com/jshttp/cookie/issues/60cookies https://github.com/pillarjs/cookies/issues/88tough-cookie https://github.com/salesforce/tough-cookie/issues/88How are you dealing with cookies having multiple identical names? E.g. when identical cookies are set from different domains.Note that this behaviour is specified by RFC 2616Multiple message-header fields with the same field-name MAY be present in a message if and only if the entire field-value for that header field is defined as a comma-separated list [i.e., #(values)]. It MUST be possible to combine the multiple header fields into one "field-name: field-value" pair, without changing the semantics of the message, by appending each subsequent field-value to the first, each separated by a comma. The order in which header fields with the same field-name are received is therefore significant to the interpretation of the combined field value, and thus a proxy MUST NOT change the order of these field values when a message is forwarded.

Submitted February 25, 2020 at 10:44AM by yvele

Alternative to JSON Web Tokens?

TLDR: Macaroons, PASTO or Branca instead of JWT?I'm learning JS and NodeJS right now. For a capstone project to show potential employers, I want to create a data gathering database with a Login and various users have different levels of authority within the application. Base level user should be able to enter computer specs into a database and advanced users should be able to monitor entry progress, overall progress, and pull reports of various kinds. A crazy ambitious project, I know.I had initially thought JWT, because I don't know any better. However, after seeing "Don't use JWT" I am left wondering the best alternative.

Submitted February 25, 2020 at 10:10AM by aladinthewoods

Monday 24 February 2020

SMF: Microservice factory framework

https://github.com/krawa76/smf

Submitted February 25, 2020 at 06:38AM by krawa76

Knexjs calling db function.

Hi everyone,I'm not getting any clue to call or select the Oracle function from knexjs.Can anyone help me?

Submitted February 25, 2020 at 06:51AM by follow2vivek

I created r/LearnTypescript, a community dedicated to learning the wonderful Typescript language! Have a Typescript tutorial you're particularly proud of? Post it here! Want to learn Typescript? Ask here! Anything in between? You guessed it-post here!

https://www.reddit.com/r/LearnTypescript/

Submitted February 25, 2020 at 05:38AM by nas5w

JavaScript heap out of memory

Hello!I'm using mysql2 with a transaction to insert 1,000,000 of rows and node crashes with a JavaScript heap out of memory.The records are simple, an integer, a date, and four doubles, about of 39mb of data for 1,000,000 of rows.This is the code inside the transaction:await arr.map(async (row, index) => {await conn.execute(sql, row).catch(e => {log.index = index;log.row = row;log.errorMessage = e.message;logError(log_id, log);throw new Exception('Error inserting data');});});to I'm starting node with --max-old-space-size=4096"scripts": {"dev": "cross-env NODE_OPTIONS=\"--max-old-space-size=4096\" nodemon index.js"},Is there a better way to deal with this situation? Can I flush the GC before run the transaction? If so, how?Increase the --max-old-space-size isn't an option, I'm looking for a way to optimize.It could be nice to be able at least log the error in the database, but if node is already crashed... :/​Thanks in advance!

Submitted February 25, 2020 at 03:27AM by jjvgarcia

Multiple updates to MySQL tables using Sequelize?

Hello to all! Looking for help for anyone that might be familiar with Sequelize.I'm trying to resolve a problem between two tables where it's a One To Many relationship. Basically once many customers have been created, I need to be able to save each customer to one booth. Each booth has many customer_ids, and each customer has one booth_id.My problem is my new Booth instance doesn't create a new booth_id which means I can't update my customer_id for each customer. Kinda stuck on where to go from here.Below is my post statement!// Post new customer app.post("/customers", (req, res) => { const { tableData } = req.body; db.Customers.bulkCreate(tableData) .then(customers => { const newTable = db.Booths.build(); customers.forEach(customer => { customer.update({ booth_id: newTable.booth_id, active: "true" }); }); newTable.save(); }) .catch(err => { console.log(err.message); }); }); This is what gets log in the console Executing (default): INSERT INTO `Customers` (`customer_id`,`customer_name`,`customer_phone`,`active`) VALUES (NULL,'customer1','1111111111','false'),(NULL,'customer2','2222222222','false'); [0] Executing (default): INSERT INTO `Booths` (`booth_id`,`active`) VALUES (DEFAULT,?); [0] Executing (default): UPDATE `Customers` SET `booth_id`=?,`active`=? WHERE `customer_id` = ? [0] Executing (default): UPDATE `Customers` SET `booth_id`=?,`active`=? WHERE `customer_id` = ? Any ideas?

Submitted February 24, 2020 at 11:42PM by kingducasse

Looking for examples of custom middleware usage

I’m trying to find some examples of custom middleware used in a production application.I understand how to create and use a custom middleware but I am struggling to think of ways to apply them.For example, could I use a custom middleware function to authenticate a user’s access token before a route is called? This may be a bad example but the gist of the question is authentication.Thanks!

Submitted February 25, 2020 at 12:03AM by skidmark_zuckerberg

You don't (may not) need Lodash/Underscore: List of JavaScript methods which you can use natively + ESLint Plugin

https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore

Submitted February 25, 2020 at 12:04AM by MaoStevemao

async await unexpected results issue

I have a recursive function that pulls a set of pages from an API. The end results are being lose somewhere along the way.The pages are paginated and i am using the parse-link-header npm library to process the series of headers. Once all the pages have been retrieved it should return the array list back. Instead I am ended up with the value being undefined.I can give a simplified version of my code, but I don't know of any free apis that have this paging style setup. The api that I am using is private so I can't give the exact code that I am working with as an example.the recursive function is:const getAll = async (params, results = []) => { try { const resp = await axios.get(params.url); for (const data of resp.data) { if (data.cond === params.cond) { results.push(data); } else { params.missed += 1; } const links = linkParser(resp.header.links); // parse-link-header library if (links.next) { params.url = links.next.url; await getAll(params, results); } else { return(results); } } catch(err) { console.error(err); return([]); } } This function is called from another function like so:const processRecs = async (cond, days = 90, id) => { const startDate = moment().subtract(days, 'd'); const params = { url: `users/${id}/records?start_date=${startDate}', cond: cond, }; const records = await getAll(params); // shouldn't need to pass an empty [] as that is default console.log(records); }When that function is used records come out as undefined always. I've added in console.log statements that show that I am getting results from the API and they are happening in order. if I add a console.log(results) right before the return(results) in the first function I can see all of the results, but they aren't being assigned into records in the second function.I am completely lost as to what is going on here. usually with async await my issue is that something isn't waiting, but here I can watch the different api calls go out one after another and see the responses come in so that isn't the issue here.any help would be greatly appreciated.

Submitted February 24, 2020 at 08:23PM by coraxwolf

How to create zsh like behavior in a Node CLI app?

I am writing a CLI app with Node. What I want to be able to do is use the up arrow key to go through a command history and allow the user to edit the command.Another example: There is a zsh plugin that will highlight a command in green if it is a valid command, as you type it. I imagine this involves re-writing the user's input with some control codes to make part of the text green.I'm using the readline module to read user input in the Node app, is there a way to get behavior like this?I guess basically what I'm trying to do is alter the command being typed in some way.

Submitted February 24, 2020 at 07:33PM by thinksInCode

Sorry, I have to tell somebody- I am absolutely loving AWS RDS (PostgresQL) right now, and not sure I'll ever use anything else (at least on personal projects).

I've done the whole MongoDB thing, and I like it. It's a great solution for many things but mostly I like how quickly and easily it can be set up.I've also done a good amount of MySQL on personal projects, after installing it on a DigitalOcean droplet (Ubuntu) and connecting to it remotely ($5/month).But I just tried AWS RDS last night, and got a plain PostgresQL (free tier) instance going... and it's amazing. Connecting to it in my project was super easy, and I absolutely love node-postgres.com as a resource when getting started. Shows you how to do clients, pools, and paramaterized queries- everything you need to get going.But anyway not to sound like a salesman but I strongly recommend looking into it, especially if you prefer relational databases. AWS RDS + MySQL I'm sure is great too. It's fast, generous free tier, and they manage the instance for you- automatically create replicas, update the software when necessary, support auto-scaling... combine that with pgadmin4 and you're in for an amazing database experience for Node projects.

Submitted February 24, 2020 at 06:54PM by zachwhitedev

Recreate a web application with MEAN stack.

I am trying to recreate aweb application( link below) with MEAN stack. Is this possible or I need a more powerfull framework?. I noticed this developer used Ajax for his website, but I would like to use other framework. Is your suggestion to recreate this web application with an advanced framework that can upkeep with the rapid growth of web development?https://www.habbousdf.com/pts/?__cf_chl_jschl_tk__=fff3e908a53f023cfed5935c461aa34c818937f5-1582568299-0-Ace7Zf9YOglpj5U03cF2TXPeAqf38D57fkXZ1

Submitted February 24, 2020 at 06:25PM by DevotoHabbo

Top 5 CSS Framework 2020 - W3hubs

https://blog.w3hubs.com/top-5-css-framework/

Submitted February 24, 2020 at 05:45PM by w3hubs

Node.js to provide CLS-like API in core

https://github.com/nodejs/node/commit/9c702922cdcf830cedb92d51e5dc9f956584c3ee

Submitted February 24, 2020 at 05:27PM by ecares

JSON Parse with Underscores

Hi,Just starting to use node.js and trying to get the value of liquidity_score from the json below.https://api.coingecko.com/api/v3/coins/bitcoin.jsonIf I try to get any value from a object with a underscore in it doesn't work. I've tried searching the web but is there something really simple I am missing?const https = require('https'); const httpGet = () => { return new Promise(((resolve, reject) => { var options = { host: 'api.coingecko.com', port: 443, path: '/api/v3/coins/bitcoin', method: 'GET', }; const request = https.request(options, (response) => { response.setEncoding('utf8'); let returnData = ''; response.on('data', (chunk) => { returnData += chunk; }); response.on('end', () => { resolve(JSON.parse(returnData)); }); response.on('error', (error) => { reject(error); }); }); request.end(); })); } async handle(handlerInput) { //const speakOutput = 'The Bitcoin price today is'; const response = await httpGet(); const speakOutput = response.liquidity_score; return handlerInput.responseBuilder .speak(speakOutput) //.reprompt('add a reprompt if you want to keep the session open for the user to respond') .getResponse(); } };

Submitted February 24, 2020 at 04:40PM by spenana

MongoDB announced GraphQL integration in MongoDB Stitch

https://blog.graphqleditor.com/mongodb-stitch-graphql-integration/

Submitted February 24, 2020 at 03:20PM by oczekkk

Instead of GraphQL, call SQL/ORM queries directly from your React/Vue/Angular code

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

Submitted February 24, 2020 at 01:29PM by brillout

Moleculer v0.14 — Making Microservices Accessible for Everyone

https://medium.com/moleculer/moleculer-v0-14-making-microservices-accessible-for-everyone-eadeefa5156c

Submitted February 24, 2020 at 12:46PM by andre_mazayev

NodeJS in Visual Studio 2019 Getting Started

https://youtu.be/IsZVBc5wZTw

Submitted February 24, 2020 at 11:55AM by monsterboz

Reading and storing csv data in node.js

https://medium.com/javascript-in-plain-english/how-to-read-a-csv-file-in-node-js-305b94e75024

Submitted February 24, 2020 at 12:01PM by Well_Gravity

Do I need to use fastify plugins in NestJS with fastify adapter?

if so, how do i achieve this? there is no mention about it in docs, nor i found any article about it, and i assume that fastify adapter takes care of nestjs packages itself.. but i still need clarification. thanks in advance

Submitted February 24, 2020 at 11:08AM by warchild4l

How to Install Nodejs and npm on Mac or Linux

https://www.stanleyulili.com/node/how-to-install-node-and-npm-on-mac-or-linux/

Submitted February 24, 2020 at 11:16AM by Stanulilic

API Endpoints

Is there a tool to identify API endpoints for an application? Or do you have to rely on documentation?

Submitted February 24, 2020 at 10:51AM by wazzalk

Utterly confused with window.myApp = {};

Hi guys, I'm relatively new to node.js.I installed a demo app based on OnsenUI and Cordova. In the main app.js, the guy declares "window.myApp = {};" and then he has various controllers and services in separate modules, which he addresses as myApp.controllers and myApp.services.I've never seen this "framework" before and can't find anything on Dr. Google on what this is.Can anyone help me with some pointers so I can udnerstand this better?ThanksGert

Submitted February 24, 2020 at 10:15AM by gwza

NPM CLI module not found

How I Compiled Koa With Closure

https://medium.com/@art_deco/how-i-compiled-koa-with-closure-63c064d7fa36

Submitted February 24, 2020 at 10:22AM by CactusOfPower

Conditional expression evaluator, some kind symbol interpreter needed

TL;DR; I am looking for some kind symbols interpreter which allow to evaluate conditional expression given as a string.Details:There are rules given in JSON file, which look like:x==0 and y==0 then z=0x==1 or y ==1 then z=1x==1 or (y == 1 and x == 2) then z=3So it just 'if conditions then do', variables are numbers and strings, and it contains mostly equality operators. x,y,z are some variables already in code. Expression scheme can be adjusted (this is flexible right now), only limitation is that it needs to support AND, OR and parentheses.

Submitted February 24, 2020 at 09:50AM by kszyh_pl

The 'testing in production' trend explained with Node.js demos

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

Submitted February 24, 2020 at 08:17AM by yonatannn

Sunday 23 February 2020

"Properly" installing local packages within a monorepo?

I'm currently working on a project which I've decided to split up into multiple packages, it has a "main" module which other modules can be added into. To do so I've a test app which installs the main and sub modules and passes the sub modules into the main oneThe way I installed my local packages is using (relative) paths, so npm install ../packages/[...], however this approach has various issues:1) Obviously for starters, my package.json refers to the path where the given module resides locally instead of pointing to a version and thus needs fixing before publishing2) The dependencies of the installed sub-modules are not installed into the node_modules directory of my application but rather into the seperate node_modules directory of the given installed package, this causes various issues like cli apps of the sub modules not being available, the sub modules being unable to require modules that I've installed in the top / test app and so on.Is there a way to do this in a "correcter" fashion? The only ideas that I've had would be to push all the stuff to a (local) git / npm server and install from there, however that seems way over the top and also like a massive hassle because I'd need to re-push/download on every change. I've also checked out of npm install maybe has some arg to fix this but no luckThanks in advance!

Submitted February 24, 2020 at 06:02AM by kinsi55

Trying to get an old npm package to work.

Im trying to run appium scripts directly on my Android phone. There's a package to do this called termux-appium, however it hasn't been updated since 2018. When I try to run a script using this package I get `"class constructor BaseDriver cannot be invoked without new"` It apparently has something to do with outdated packages and latest node version (cannot install older node version on termux), possibly outdated babel loaders but I know nothing about any of this stuff. I looked a the code and the basedriver is indeed being invoked with `new` so not sure why this error comes up.I was wondering if this might actually be a rather simple fix that I'm just not familiar with. Does this error suggest a simple babel issue?

Submitted February 24, 2020 at 01:10AM by RupFox

Announcing an Official Node.js Client for the Sight API

https://siftrics.com/blog/announcing_official_node_js_client.html

Submitted February 24, 2020 at 12:02AM by siftrics

Made npm package to decrypt passord protected pptx file

The pptx files can be opened in editable mode, event though it was password protected. This is supported only till Office 2016 version.The source is here. This is my first npm project, so here I have a question that, I need to pass the file name(without pptx extension) as argument. But if the user choose to press tab for auto completion then it would result something like .\fileName.pptx in windows and in linux as fileName.pptx.So what approach should i follow to parse fileName from the above exptension(.pptx) varients. Parse differently based on os or use libs like command-line-args etc.

Submitted February 23, 2020 at 09:14PM by zaerrc

Question on validation vs sanitation

Hello node community!I am a network engineer learning node/express/mongoDB. Programming / software security is not my expertise.I am using Joi for input validation and mongoose for storing/querying data from mongoDB.I am currently following Mosh Hamedani's lessons regarding backend programming but have not seen anything on sanitizing input to mongoDB. I have also not heard of a NoSQL injection attack, and am very aware that blissful ignorance does not equate to security. This 4 year old link from stack overflow discusses it briefly however I would like to know how mongo sanitation stands today.Are there any good NPM packages that you all would recommend that would be friendly for a learner. I suspect that helmet will not be enough to cover me for a noSQL database such as mongoDB, and is more intended for CSRF / XSS etc.

Submitted February 23, 2020 at 08:49PM by Deadlydragon218

I'm beginner, is that a good choice to organize a project

Hi,I'm a beginner to nodejs, and i want to write a simple first API.I want to organize my projetc with a multi layered design. folders are like this : middlewares -> logger, authentification... repository -> call to the database routes -> all the routers services -> the business logic app.js -> entry of the appwhen an action is done I follow this schema :app.js -> routes -> services -> repositoryand I do this for exemple :router : ```javascript const service = require("../services/users");router.get("/", (req, res) => { service.getAll() .then(data => res.json(data)) .catch(err => res.send(err)); }); ```service : ```javascript const {repository} = require("../repository/users");const service = {getAll: async () => { // SOME BUSINESS LOGIC HERE try { return await repository.getAll() } catch (err) { throw new Error(err); } }};module.exports = service; ```repository : ```javascript const repository = {getAll: async () => { // CALL THE DATABASE AND PUT RESULT IN users[] if (users) { return users; } else { throw Error("can't recept users"); } } };module.exports = repository; ```My questions are : - Is it a good practice / common practice to multi-layered with nodejs ? - I don't want to use es6 classes at this time, I put some methods (getAll()...) in objects (repository, service...) and exports them, is it ok to do that like this ?Thanks for your response, and sorry for my english it's not my first language...

Submitted February 23, 2020 at 08:58PM by bloodgast

Request module has been deprecated?

Just went on npm and was shocked to see this warning saying that the module had been deprecated. Seem we might be getting a completely new request module, one that is rewritten.

Submitted February 23, 2020 at 08:03PM by I-Am-Programmer

Socket.oi button examples please

Please help,I am trying to get my head around Socket.io and need an example using more than one button. Pretty much every example I've come across so far for Socket.io has been a bloody chat app !!I literally need a super simple example of 2 or more buttons on a web page and what I need server-side to detect which buttons were pressed, nothing more complex than that. This will help me understand it all.Thanks in advance,Mike.

Submitted February 23, 2020 at 06:33PM by TheArduinoGuy

User accounts express best practice

Just wondering how do you easily add user accounts and authentication to your express app?Is there something as comprehensive as asp.net identity where a security expert team takes care of keeping the password hashing stuff up to date and using best practices?Or are we stuck with rolling out own probably-dodgy passport local strategy boilerplate code every time?

Submitted February 23, 2020 at 04:33PM by Fuzzy-Attention

A library to manipulate xattr on macOS

I've published a library to help manipulate xattr on macOS. Furthermore, this library provides some cool function such as setting a custom icon for a file, parsing kMDItemWhereFroms property provided by macOS.You can implement a lot of native features with this library. Try it out!https://github.com/vincentdchan/node-xattr

Submitted February 23, 2020 at 02:19PM by okcdz

What exposing a port in Docker does, and doesn't do

I was unsure what exposing a port in Docker does. Since you can also publish a port, I wondered what the difference between exposing and publishing is.Should I use expose to allow two containers to talk to each other?Does it make a container accessible from the outside world?The information I could find online wasn't very accurate. There's a highly-upvoted and accepted answer on Stack Overflow that's partly incorrect. And in the official docs, there's an outdated section so filed a PR to update it.I wrote this article to save someone else the time and confusion I had to go through:https://maximorlov.com/exposing-a-port-in-docker-what-does-it-do/.Hope you find it useful. Have a nice Sunday!

Submitted February 23, 2020 at 01:41PM by _maximization

React Node AWS Scaling MERN Stack Full Project

https://www.udemy.com/course/mern-react-node-aws/?couponCode=74CF6DC3669B8071296F

Submitted February 23, 2020 at 12:05PM by kaloraat

Get commit hash of a node package

Hey there,Is it possible to find the git commit that an npm package being used in your project is based upon ? What would be the smartest way of doing that ?Imagine for example that my project depends on webpack v5.0.0-beta.5. On github that version is available here, commit hash is 85145cebf3ed50014b36e76047681bbb066bbe1f. Some research seem to indicate that no versioning info is kept at all.Is this possible ?

Submitted February 23, 2020 at 11:02AM by Alistesios

How to test typescript code inside docker

So, i write in typescript, and i have dockerfile, where i have multi-stage build, one stage is where i build my typescript code, and second stage is where i copy that built code and run my application. i have tests up and running, one problem is that i only tested in development environment. but i want to change that. so how would i do that? should i test my code before building, and if it passes, then build and move to second stage? obviously i would do something like that with CI provider.. or is there any other approach to this?

Submitted February 23, 2020 at 10:24AM by warchild4l

NodeJS Security Deep Dive

https://www.andreigaspar.com/nodejs-security-deep-dive/

Submitted February 23, 2020 at 07:15AM by harlampi

What should I know about PostgreSQL if I am switching from classic PHP/MySQL stack to nodejs? Is there any SQL nuances on Postgresql?

No text found

Submitted February 23, 2020 at 07:48AM by xoxaxo

Saturday 22 February 2020

Windows Install

Is the 64-bit Node.js installer on Windows still a cluster fuck? The last time I installed node.js was circa version 11. In the install I checked to install additional tools, because I thought I would need them to use sqlite3. During the install, my computer was automatically rebooted at least a dozen times and I thought the installer hosed my Windows install. After I regained control, I had boxstarter and chocolatey installed. I have since removed node.js (boxstarter remains, the unistaller isn't present and didn't search the web to fully purge it). I'm considering installing node.js on Windows because I like the Windows version of Visual code better, but am wary of installing it again.

Submitted February 23, 2020 at 04:27AM by SlowFatHusky

Querying a site behind a proxy

So I need to implement a proxy that redirects from my localhost to another website (for example, google or a public test endpoint such as httpbin). I've tried using both http-proxy-middleware and express-http-proxy and I end up getting a 400 error when I attempt to do a GET request to the proxied url. Anyone have any experience with this? I assume something is wrong with my headers when I send my GET request as logging has shown the proxy is set up successfully. Kind of a last resort for me as I havent been able to find much online.

Submitted February 23, 2020 at 03:57AM by AltruisticPenguin

Advice architecture

Hi guys,Im on this project where I have different endpoints (auth basic) available which I don’t have any control on them and I would like to add some authentication and authorization systems to those endpoints, I was thinking on create another express api that will secure any request to those endpoints. So basically an api that will contact another api, any thoughts about this kind of approach?Thank you all

Submitted February 23, 2020 at 01:29AM by Degordian

Here's my app made using node and express - a multi-room chat app with image uploading

https://foxxit.xyz

Submitted February 23, 2020 at 02:07AM by OP_IS_A_LEGEND

I made my first web app in node/express - Ecommerce website

This is my first web app in node made with Express/Pug/Bootstrap/PostgreSQL and light use of VueJS:https://young-coast-13128.herokuapp.com/Test user if you don't want to sign up:user: Redditpassword: reddit123It's a fake smartphone shop. I'm still learning design concepts so it doesn't look great. It's also in Portuguese, my native language.I'd like to receive some feedback. Thanks in advance.

Submitted February 22, 2020 at 10:59PM by GShadowBroker

Micro service architecture with NodeJs

Hi, I want to develop a project with NodeJs and MySql as the backend language and the project consists of multiple services so instead of creating a monolithic app I was thinking to create a micro-service based architecture. So can anyone please help me to create the micro service architecture?I was thinking of creating a controller service which will receive the request and then give it to the Authentication layer and once validated it will route it to the specified micro service. I was thinking of running individual services as a independent node app on different ports with their own APIs. The controller service will invoke those internal APIs. To deploy I was thinking to create multiple linux service files and start all services with “systemctl” command.For authentication I was thinking of using JWtokens for invoking the APIs and then call other internal micro services with their own service to service username password authentication.Is there anything that I am doing wrong? Is there anyway I can improve the security of this project?

Submitted February 22, 2020 at 07:16PM by Pronoy999

Can I get someone to give me their opinion about this code and it's error handling?

Im using my weekends to get better with NodeJs/Express. I don't work with anyone who knows NodeJS at a professional level so I am looking to the fine people of r/node for criticism!Outline:I have created a user in my Mongo database. In this example I am signing that user in, and responding with a valid JWT token upon a successful password match.It requires a few async functions: mongoose.findOne(), bCrypt.compare(), and jwt.sign() and each one of these functions can return an error as most know. In the code block below, I am nesting bCrypt.compare() inside of findOne(), and then jwt.sign() inside of bCrypt.compare().My main questions here are with the error handling. I don't feel like this is right, especially with all of return next() 's being used in the catch blocks. I suppose their might be a better way, but at my current abilities, it seems like the best way to handle each different error condition. For all I know, there is nothing wrong with what I am doing here.Here is the sign in controller: https://pastebin.com/DhU760mcHere is my generic error handler called by next(): https://pastebin.com/YxhA6cTNHow would a more professional level of understanding handle this?

Submitted February 22, 2020 at 06:53PM by skidmark_zuckerberg

Need help with JWT Auth + Black-/Whitelisting

Im working on an api server (express with mongodb) and implemented JWTs with refresh tokens for authentication.I want to be able to blacklist Tokens, in case someone changes his password, gets hacked or banned.​I thought about storing a blacklist in redis, using the jwt as a key. But how would I identify a token by the username then?Users should also be able to be logged in on multiple devices, so I can't use the userid as a key.I guess I would need to store all JWTs of the user in their mongodb document, but then I could just as well use the mongodb as a whitelist, right?Then I would also have to remove expired JWTs from the whitelist. In redis I could just set the expire time, which I would prefer.​What would be the cleanest and simplest solution for this?

Submitted February 22, 2020 at 06:38PM by kevgk

Suggest a web of things projects

No text found

Submitted February 22, 2020 at 12:22PM by vinay_nb7

Any advice/resources to help me learn and create a web project in node.js?

I am a sophomore college student taking a web programming class but we are learning PHP using apache server which I heard is old technology. We have to make a project at the end of the class and I don't want to use dying tech. However, I have no experience with node.js and Javascript. My roommate who has a lot more experience in programming, told me to make a project with node.js. He told me I just need to learn how to use express, send html files, and client side JavaScript/JQuery.I have about 8 weeks to make a project. I am planning on just making a simple website of my portfolio unless if I think of a better idea.I am very new to web development besides basic knowledge of html and css. I don't know a lot of the terminology of what my roommate told me nor do I have a good understanding of the concepts of node.js.Anyways. I just wanted to ask if anyone has any advice for how I should start and what direction to take to make a node.js project. I am also open to new project ideas and resources to help me learn. I apreciate any feedback.

Submitted February 22, 2020 at 08:24AM by Datstructure

GitHub - hafizmuhammadshoaib/express_ts_boilerplate

Hello folks,I have just created a boilerplate of nodejs express framework with TS, TypeORM and Swagger docs. Check it out and let me know what could be improved.https://github.com/hafizmuhammadshoaib/express_ts_boilerplateThank you !

Submitted February 22, 2020 at 08:25AM by shoaibsilat

Encrypting & Decrypting data with Node.js built-in library called crypto

https://www.htmlhints.com/article/71/encrypting-decrypting-data-with-nodejs-built-in-library-called-crypto

Submitted February 22, 2020 at 07:33AM by harry719

Friday 21 February 2020

Winston logger, what I am doing wrong? if I call process.exit(0) winston didn't write log to file, without process.exit(0) works fine.

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

Submitted February 22, 2020 at 06:27AM by xoxaxo

Can someone help me why this doesn't work?

const jq = require('jquery'); const mysql = require('mysql'); const con = mysql.createConnection({ host: "localhost", user: "root", password: "password", database: "votesystem" }); $(document).ready(function() { $("#votes").click(function() { con.connect(function(err) { if (err) throw err; var select1 = $('#sel1').find(":selected").text(); var select2 = $('#sel2').find(":selected").text(); var sql = "INSERT INTO voters (votername, votercomment) VALUES (select1, select2)"; con.query(sql, function (err, result) { if (err) throw err; alert("Voted successfully!") }); }); }); }); When I click the button, nothing happens in the database and alert msg doesn't show up.If it's not possible, how should I tackle the problem?TIA.

Submitted February 22, 2020 at 05:14AM by DecentTaro

MEAN Stack Angular 9 Build Realtime CRUD Web App Quickly

https://www.djamware.com/post/5e50b735525fc968b04a707f/mean-stack-angular-9-build-realtime-crud-web-app-quickly#.XlDCueuAWao.reddit

Submitted February 22, 2020 at 05:57AM by didinj

Reading bmp file (without external packages)

Ok so i am reading a bmp file with fs and a buffer and im getting the raw data just as i need it (hex data), but once i store it in an array or print it to the console it changes formats from hex to an 8bit integer. How do i get the original hex value out of the buffer without it changing?Thanks in advance.

Submitted February 22, 2020 at 01:43AM by rogwf259

Sequelize - having trouble creating self referenced M:N relationships

I am trying to allow my users to block other users and while it is an easy thing to do in pure SQL (jjust create a Blocks table with two foreign keys) it is a pain in Sequelize.​My user model is:const User = sequelize.define('Users', {UserID: {type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true},//snipped attributes that are not part of the primary key});Then I doUser.belongsToMany(User, {through: 'BlockedUsers', as: "Blocks"});which does not result in the BlockedUsers table being created. In fact NOTHING changes in the DB structure doing that.I have also tried doing a "two-way" relationship as it is usually done with normal relationships likeUser.belongsToMany(User, {through: 'BlockedUsers', as: "Blocks"});User.belongsToMany(User, {through: 'BlockedUsers', as: "Blockeds"});It also does nothing. The DB is created as if there were no relationship.No errors are thrown using any of those ways.​Am I doing something wrong? Do I need to define en empty model named BlockedUsers for that to work?​Note: I am using SQLite for prototyping purposes but it is not supposed to be the culprit here.

Submitted February 22, 2020 at 12:09AM by Kran6a

Software design patterns relevant to Node?

What are some software design patterns that are relevant to Node? Why are patterns like dependency injection frowned upon in JS?

Submitted February 21, 2020 at 10:32PM by deploy_on_friday

Code Reviews (JavaScript)

Will someone like to do my code reviews of javaScript or nodejs?

Submitted February 21, 2020 at 10:42PM by mian_m

redturn.ts - Event-based/Queueing redis mutex lock in typescript

https://github.com/kevinwilson541/redturn.ts

Submitted February 21, 2020 at 09:58PM by kiadimundi

Three Angular+Node Productivity Web Apps Open Sourced

https://www.eviratec.com.au/2020/02/22/three-angularnode-productivity-web-apps-open-sourced/

Submitted February 21, 2020 at 09:23PM by subspacemonkey

[buying] the airdropped coins you did not know you had

The adventures of deploying a Node Js server please help :(

Hello guys so for the past 48 hours or so ive been "simply" trying to host a node js server on Digital Ocean where i am using express js for incoming request payloads . For the client side i am hosting a website separately on firebase that hits the end points to retrieve the data to be displayed on the front end .The end points work fine via HTTP locally HOWEVER when i try to deploy into production in order to avoid any CORS issues from the research ive done so far all these request must be HTTPS for security reasons but when i do so i receive no data back from the api I just get "Failed to load resource: net::ERR_CONNECTION_CLOSED" and its been driving me crazy haha.I've done tons of googling and some people have said i need to set up the DNS on my web host to the IP i received from Digital Ocean but that dosent make sense to me since i am hosting my website somewhere else and not Digital Ocean. I've also read something about having to set up proxys? Anyways if anyone has done anything like this before I'd appreciate the input thanks .​TLDR: How do I make a Node Js express server hosted on digital ocean accept request from a different host in this case that host being Firebase

Submitted February 21, 2020 at 08:16PM by AquaHug

How to create a transaction payable by venmo OR apple pay?

Hey guys, I'm trying to make a bill splitting app, and my goal is to have the person that paid the bill send out links via sms that prompt the people that owe them to pay, with options venmo OR apple pay.I'm currently looking at plaid, braintree, and stripe connect, and having trouble figuring out how to integrate all of it together. Any help or advice would be appreciated!

Submitted February 21, 2020 at 07:29PM by TheRealSteven

Display RSS feed on Vue.js Frontend

I want to display a series of articles from a Google Alerts feed. I got it working in Javascript. How do I convert my frontend as a Vue.js component and display it on my Vue.js application?Here is the code:Client: Test page

Latest articles

Backend:const feedparser = require('feedparser-promised'); const express = require('express'); const app = express(); const server = require('http').Server(app); const io = require('socket.io')(server); const fs = require('fs'); server.listen(8000); console.log('Server started on localhost:8000'); let url = 'https://www.google.ie/alerts/feeds/10663948362751557705/4511034072220974544'; // Declare a variable for the feed content let feed = []; // Parse the feed feedparser.parse(url).then(items => { // Update the variable with the new data for (const [i, item] of items.entries()) { // Retrieve the ten first elements, with their title and description // And add them to the feed array if (i < 9) { feed.push({ title: item.title, link: item.link }); } } // Write it to a file so you can know how to parse it better // The callback is mandatory, but it's useless here fs.writeFile('feed.json', JSON.stringify(items, null, 2), 'utf-8', (data) => {}); }); // Define the default route app.get('/', (req, res) => { // Render the page res.render('test.ejs'); // Send the data to the client using socket.io io.on('connection', io => { io.emit('feed', { feed: feed }); }); });

Submitted February 21, 2020 at 06:09PM by RyboXBL

Ahaless: write serverless application OOP on top of Typescript

https://medium.com/@linrium/ahaless-write-serverless-application-oop-on-top-of-typescript-ffbab8e5c4db

Submitted February 21, 2020 at 05:25PM by linrium

Thoughts about async / await

I've been reading many posts about new async / await feature in JavaScript and find that not many people are fine with it. More interestingly people trying to reinvent the wheel like overwriting native implementation etc. `awaity` do this to some degree, and not everyone can't quite get understand why to put `bluebird.js` in your project. Still, there is always room for improvement.I wrote a small piece of code many years ago and put it into the npm library recently. This code traveling from project to project. You can find it very tiny and very useful - https://of.js.org/. It upgrades your promises with some basic features. First, it adds timeouts for your async operations which will be appreciated by jQuery and `axios` users. And of course, there retry option. You can define your default value in case of error or override error with your own (different message for user in the example). And most useful is to get rid of unnecessary repetitive try / catch code.I was inspired to write this after reading these posts:https://www.reddit.com/r/node/comments/dpzsv1/beginner_forcing_asynchronous_functions_to/https://www.reddit.com/r/node/comments/f3kfqo/how_do_you_handle_async_await_errors/https://www.reddit.com/r/node/comments/f3dzut/javascript_callback_promise_and_asyncawait/https://www.reddit.com/r/node/comments/f46rdz/how_to_rewrite_code_using_async_and_await_in_node/

Submitted February 21, 2020 at 04:27PM by r37r0m0d3l

Koa vs Express WITHOUT the BS

https://www.stackchief.com/blog/Koa%20vs%20Express%20

Submitted February 21, 2020 at 04:09PM by stackchief

How can i make node offline temporarily during a unit test?

With in a unit test scope i like to make sure all http/https request fail and throw exception if any. I have scenario to test API that suppose to be only called in offline scenario and should not fail if there is no internet. But developer can tend to change low level api and might make rest call for what ever reason. So i like to PR to fail if that ever happen.Given i cannot mess with the CI-Job or vm that it run on. One idea someone gave me was to pollyfill http/https (only interesting in these) function that is use to send request to throw exception and restore them after the offline scope is over. If you guys agree then what is the function i should shadow/override that will helpful in achieving that.Those who will say firewall for the process should know part of the test download data from internet and then other part uses the data and should work offline

Submitted February 21, 2020 at 03:32PM by khanaffan

Building a secure web server with Node.js

https://www.grizzlypeaksoftware.com/articles?id=JDcsPW2raSic6oc6MCYaM

Submitted February 21, 2020 at 02:38PM by grizzlypeaksoftware

WebSocket Sessions: A WebSocket-based API / tunneling server & client libraries

https://github.com/monicanagent/websocketsessions

Submitted February 21, 2020 at 02:10PM by monican_agent

advice for using node js framework

hello developersi'm looking for good framework not just express js to use in coming projects that will need the use of node js and i need a good framework with long term support and nice documentation and community i foundnestjs but it's similar to angular which i don't prefer andloobback andadonisJs which look great but for some reason it's not used enough​any recommendation will be helpful thanks

Submitted February 21, 2020 at 12:44PM by The_GlitchX

a relational database with no schema and no joins hell

these last days i found out about the prolog language and became obsessed with knowing everything i can about it, i still don't have an accurate picture about how it is being used in real world solutions despite the few examples i found online.Then in my continuous search spree, i found out about datalog and found this AMAZING video https://www.youtube.com/watch?v=oo-7mN9WXTwI instantly fell int love with the idea, this type of database can technically emulate all types of databases, it can basically do anything, it is immutable, so you have the entire history, and you can go back in time to a certain point and act on the database as it was at that point in time. It can work as a relational database, but with no rigid schema, and with no need for complicated join queries all over the place, it also can go forward and backwards without needing to define the relationship both ways.the speaker talks about datomics(for backend aimed directly at java and clojure, it has third party drivers for other language but most of them weren't updated in 7 or 8 years), and datascript (a front end implementation to manage data in browser).I am just wondering what you all think about this, and why this hasn't been implemented in more solutions and isn't more widespread, i would love to work with a database like this it seems so full of potential.

Submitted February 21, 2020 at 11:30AM by biggy_sauce

Really Node.JS is the perfect tech environment for the building of an E-commerce Website? - Hire Web & App Developers

https://www.inwizards.com/blog/really-node-js-is-the-perfect-tech-environment-for-the-building-of-an-e-commerce-website/

Submitted February 21, 2020 at 11:46AM by bakeryindore

[Vue] browser base: speech to text online tool

https://parse-nuxt-speech.herokuapp.com/

Submitted February 21, 2020 at 10:07AM by bananajsjs

SocketIO: Can hackers send manipulate events to the backend?

If I have something like thisio.on('connection', (socket) => { socket.on('join_room', () => { socket.join(/* ID queried from database */); }); }); Can hackers send an event to manipulate that from the front end?

Submitted February 21, 2020 at 08:30AM by eggtart_prince

Webinar: Testing in production - explained with Node.js demos

https://zoom.us/webinar/register/7615822291952/WN_yp7Fp_RnQu6stQyGiVRsGA

Submitted February 21, 2020 at 08:16AM by yonatannn

Thursday 20 February 2020

Configuring NGINX for SSR React with Node and Express with routing

I need some help configuring NGINX. Currently I am able to hit / on the browser and get the website loaded up. But then I get a 404 page from nginx when I hit it with any subroutes, e.g. /login. I have node serving all the endpoints, app.get('/*', (req, res) => {... return res.send("")}I'm handling the routes using react-router-dom and react-router-config. I'm also handling errors and reroutes in express node:app.get('/*', (req, res) => { // SSR stuff if (context.url) { return res.redirect(301, context.url); } if (context.status === 404) { res.status(404); } const { helmet } = helmetContext; return res.send( ` // more html... `, ); } This is a portion of my nginx.conf:server { listen 80; listen [::]:80; server_name 18.223.162.221; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; proxy_pass http://127.0.0.1:3000; try_files $uri $uri/ =404; } # error_page 404 /404.html; # location = /40x.html { # } # error_page 500 502 503 504 /50x.html; # location = /50.xhtml { # } } When both of the blocks error_page 404 and error_page 500 are uncommented, the sub route, e.g. /login seems to make node to capture the last endpoint in the routes array, displaying the Notfoundpage, despite that the route should've displayed the Loginpage. export const routes = [ { path: '/', exact: true, render: Homepage, }, { path: '/login', exact: true, render: Loginpage, }, { path: '/protected', exact: true, render: PrivateRoute, }, { component: Notfoundpage, } ]; Commenting both of the error_page blocks in the nginx.conf load the nginx's 404 Not Found page when hitting the browser with /login. The same can be said when only uncommenting the error_page 500 502... block.I just need to be able to render all those pages at those routes, and the Notfoundpage at any unknown routes. What am I missing in the nginx.conf? Or where else should I be looking at?

Submitted February 21, 2020 at 04:40AM by jsphkm

What Time: A Node project that finds when everyone in your team is available.

Web app: https://what-time.herokuapp.com/Github (for those interested): https://github.com/omerdemirkan/whattimeIt requires an account so if you don't want to sign up you can use this dummy account:Username: redditPassword: Reddit123Here's how it works: The user creates a survey with an event name, date, and identifier (to identify submissions). This gives you access to a sharable link. This link allows anyone to submit their available hours and name. The user can see all submissions and available times on their end.It's at a very early stage so please let me know what features you would most like to see added. Any feedback would be much appreciated!

Submitted February 21, 2020 at 03:13AM by crypto_thiccboy

[Sequelize/Postgres] Is there an option to add a key value pair (foreign key) to each object in an array when using sequelize.bulkCreate() ?

I have potentially hundreds of rows to insert via an array of objects and I need to pass in a foreign key on save but since this array is being saved within a transaction with constraints deferred I can't just go get the ID so I need it to pass it in on save (or in a way that will work within this context).Is this possible with Sequelize or will I be forced to be a programmer like they pay to be and write this myself? My problem is when i create these objects I have zero context of the parent row's primary id so I can't reference it until this array objects comes back from the module and is sent to the DB create controller where I save everything to postgres.// Parent method gets data from controller parentMethod(data) { sequelizeTransactionWrapper(transaction) { // each constraint is deferred aka the foreign keys so it won't break during this process since they all get created at the same time childMethod1({ primaryId: 123, key: data.something }, { transaction }); childMethod2({ foreignKey: childMethod1.primaryId, key: data.something }, { transaction }); childMethod3({ foreignKey: childMethod1.primaryId, primaryID: 54321, key: data.something, key: data.something }, { transaction }); childMethod4({ arrayOfObjects: [ { foreignKey: how do I add childMethod3's ID here after the objects are already created? ...more data }, { foreignKey: how do I add childMethod3's ID here after the objects are already created? ...more data } ] }, { transaction }); } } Is my best solution here to just loop the array and assign the foreignKey or is there a sequelize way to do this automatically?Sorry if it's not clear, please let me know if you need clarification.Thank you!

Submitted February 20, 2020 at 09:54PM by nullol