Tuesday 30 April 2019

Created an npm module to add PostGraphile to a Nestjs application. Love to have some feedback

https://www.npmjs.com/package/postgraphile-nest

Submitted May 01, 2019 at 06:40AM by alex-ald

Introducing deploy-node-app: Deploy your node.js app to Kubernetes with a single command. No config required.

https://github.com/kubesail/deploy-node-app

Submitted May 01, 2019 at 03:03AM by erulabs

Problems with saving changes to a session before redirect

I had a problem before where I'd try to make changes to req.session, and I'd get this error: "Can't set headers after they are sent."I found out that res.redirect was causing my issues, even though it's after req.session.x = y ... it's being called first, and I haven't been able to resolve it. I called req.session.save with the redirect inside the callback after making changes to req.session, but no dice.

Submitted May 01, 2019 at 12:36AM by Mobile_Monk

How do I go about using a token for later?

I am doing a OAuth flow for Shopify, after authentication the user is redirected to my site where I post and get a access token.But where I’m having trouble is say this user isn’t logged in my site yet or doesn’t have an account and needs to sign up, how can I save the authenticated access token for later when they do sign up or log in and I can save it under their account?

Submitted May 01, 2019 at 12:41AM by prgrmmr7

Node.js To Implement ES6 Modules At Last

https://nodejs.org/api/esm.html

Submitted May 01, 2019 at 01:05AM by N8Programs

Node-based message bus and workflow orchestration framework

Check out this Node.js message bus and workflow orchestration framework using RabbitMQ, SQS, and Postgres. Who’s composing Node-based and/or other platforms using similar architectures?https://node-ts.github.io/bus/

Submitted April 30, 2019 at 10:44PM by GandalfGunnar

Benchmarking A Node.js Promise

https://www.toptal.com/nodejs/benchmark-nodejs-promise

Submitted April 30, 2019 at 07:33PM by pmz

Best Practices For Using TypeScript with Node.js?

https://blog.bitsrc.io/best-practices-for-using-typescript-with-node-js-50907f8cc803

Submitted April 30, 2019 at 08:03PM by JSislife

Join the Stellar testnet the easy way

https://medium.com/@todkap/70ae5f1e753f

Submitted April 30, 2019 at 06:26PM by kiarash-irandoust

How do I scan RFID tags using node

I bought a USB RFID plug n play scanner and this prints the RFID tag id on any input field when I scan it, google search bar, terminal, notepad,
fields etc. How do I simply read the id without an input field?​The idea is to scan the tag, query my database and display the results on my front-end(React).

Submitted April 30, 2019 at 07:02PM by Chr0noN

Node v11.15.0 (Current)

https://nodejs.org/en/blog/release/v11.15.0/

Submitted April 30, 2019 at 07:12PM by dwaxe

Question about testing w mocha and chai

Hi i am a student and i have been learning nodejs for 3 weeks now. So for an assignment we need to make a test that checks if the right status code and (error) message are returned when a user enters a movie without a title. The requests are done via Postman and the movie json is entered in the body. I am confused how do i do this?

Submitted April 30, 2019 at 07:18PM by Savage_Kantuz

5 ways to use OAuth2 in Firebase and Google Cloud Platform

https://blog.quid.works/serverless-oauth2-flows/

Submitted April 30, 2019 at 06:52PM by snakemanuver

CMV: Node is just as good a choice as Rails when it comes to making web applications

I love Ruby on Rails. I love it because I can quickly and easily build a production ready web application within weeks or even days. It's mature, stable and has a great community. The thing I most love about Rails is that it encourages test driven development, and provides a framework for doing so out of the box. This means I know that my application works.Because of this, I'm having a really hard time convincing myself to learn Node because I'm so comfortable with Rails. However, I also know that there are so many production web applications built in Node, and that Node is a very powerful tool.My challenge is I don't know when and how to reach for Node when I could just use Rails and have the added bonus of an end to end testing framework built in. Every Node tutorial I've seen either ignores testing, or requires manually setting up a testing framework.I know there's Meteor.js which looks like the closest equivalent to Rails, but I get the sense that it's not nearly as stable as Rails. Am I wrong? Is there a stable, mature full stack Node framework out there? Or, am I just not thinking in the 'Node' way?

Submitted April 30, 2019 at 06:17PM by P013370

Calculate Standard Deviation in JavaScript

https://masteringjs.io/tutorials/fundamentals/stddev

Submitted April 30, 2019 at 05:35PM by code_barbarian

How do i set authentication token to chai-http

I have create some test cases with ran successfully however cases that need token fails.this is the error messagePOST /api/v1/auth/signinshould sign registered user in:Uncaught TypeError: Cannot read property 'token' of undefinedat token (API\src\tests/users.test.js:124:54)at Test.Request.callback (node_modules\superagent\lib\node\index.js:716:12)at IncomingMessage.parser (node_modules\superagent\lib\node\index.js:916:18)at endReadableNT (_stream_readable.js:1094:12)at process._tickCallback (internal/process/next_tick.js:63:19)this is my codeimport chai from 'chai';import chaiHttp from 'chai-http';import app from '../../server';chai.should();chai.use(chaiHttp);describe('POST /api/v1/auth/signin', () => {it('should sign registered user in', (done) => {const user = {email: 'mail@mail.com',password: 'password',};chai.request(app).post(' /api/v1/auth/signin').send(user).end((loginReq, loginRes) => {const token = \Bearer ${loginRes.body.user.token}`; chai .request(app) .post('/api/v1/auth/signin') .set('authorization', token) .end((err, res) => { res.should.have.status(200); res.body.should.be.a('object'); done(); }); }); }); });`

Submitted April 30, 2019 at 05:49PM by PearllyO

How do I deploy this app to Heroku?

I created this ( https://github.com/amirsaranBIH/calendar-app ) app with React for the client and Express for server/api. I want to deploy it to Heroku. I have to start two different servers (React client server on port 3000 and Express api server on port 3001) with my npm start script. It looks like this: "concurrently \"cd api && node bin/www\" \"cd client && npm start\"". It works fine on my localhost when I run it.What do I need to change and/or add or configure.Will Heroku use the ports that I set up. For example: axios.post('https://react-nodejs-calendar-app.herokuapp.com:3001/api/test', data). Will this still work?I also set up a proxy in the client package.json ("proxy": "http://localhost:3001"), will I have to change the host or it will ignore the proxy (it's only for development from my understanding, I only included that because I followed a tutorial).If you need more information I can provide.Detailed explanations are welcome, I want to learn this, not just follow a tutorial.

Submitted April 30, 2019 at 01:47PM by AmirSaran

Reddit NodeJs Bot Part 2 - Automated Posting on Subreddit

https://www.youtube.com/watch?v=L-ksqOGcfUM

Submitted April 30, 2019 at 01:53PM by GrohsFabian

Can you link some express rest api projects with test coverage that follows best practices?

My tests absolutely suck and I really want to see examples that are little more in-depth than the simple tutorials that I managed to find.

Submitted April 30, 2019 at 02:11PM by Kr7731

Require WebAssembly modules using script tag - script-wasm

https://github.com/mbasso/script-wasm

Submitted April 30, 2019 at 01:03PM by Teo_Basso

Simple package.json style IOC container for Node

I created an IOC container designed with simplicity and familiarity to package.json in mind. This was created to be the simplest possible way of mapping modules to their respective dependencies. Feedback on what people think of the dependency declaration-style as well as design decisions (such as auto-instantiation instead of the common factory-pattern), as well possible contenders that do the same (thus rendering it redundant) would be much appreciated. If anybody would like to comment on the technical implementation that would also be great (such as the subscriber-based dependency resolution). I think the performance could probably be increased by the use of certain log-n tree structures (instead of iterating as much as is currently done), or possibly priority queue for faster leaf-finding.Here is the package: https://www.npmjs.com/package/nano-container

Submitted April 30, 2019 at 01:05PM by booleantoggle

Everything You Need To Know About Nodejs!

https://www.yourteaminindia.com/blog/nodejs-development/?utm_medium=NodejsDevelopment&utm_source=Reddit&utm_campaign=SBM&utm_content=InternalBlog

Submitted April 30, 2019 at 01:24PM by yourteaminindia

New Features Bring Native Add-ons Close To Being On Par With JS Modules

https://medium.com/the-node-js-collection/new-features-bring-native-add-ons-close-to-being-on-par-with-js-modules-cd4f9b8e4b4

Submitted April 30, 2019 at 01:39PM by harlampi

An example of integration testing with puppeteer

https://javascriptwebscrapingguy.com/jordan-does-integration-tests-on-citadel-packaging/

Submitted April 30, 2019 at 10:29AM by Aarmora

Is Loopback 4 a decent framework vs "from scratch" express?

So we've got this new project and we are building a new stack from scratch. Frontend is well fixed and we already have solution going, now comes the backend part with a RESTful API. We have decided to give node a try.But what would be good is having quickly a good RESTful API which follows solid specifications like OpenAPI or oData and have good ORM features on SQL Server or Mongo.So I built this prototype in Loopback 4 and it seems to do the job. Problem is that everybody says that Loopback is a nightmare to maintain as everything is made so it remains under Strongloop's hand. A lot of people used to say the same of most now heavily used frameworks but I am afraid of this maintenance process when the project will be bigger.So right now I am hesitating: is it better to build an API a bit more from scratch that we will know by heart with Express or use Loopback and its magic command line which gives quickly a full solution which will be harder to maintain?

Submitted April 30, 2019 at 10:54AM by AlphaKevin667

What is causing this error?

I created a web app with React client (port 3000) and Express API (port 3001) and when I try to do a post request to an API I get this error message:Failed to load resource: net::ERR_CONNECTION_REFUSED :3001/api/test:1 createError.js:17 Uncaught (in promise) Error: Network Error at createError (createError.js:17) at XMLHttpRequest.handleError (xhr.js:87) I am sending a post request with axios in client/src/App.jsYou can find the code here: https://github.com/amirsaranBIH/calendar-app/tree/dev

Submitted April 30, 2019 at 09:27AM by AmirSaran

GraphQL Fragments and the benefits of using them

https://blog.graphqleditor.com/GraphQL-fragments/

Submitted April 30, 2019 at 09:19AM by oczekkk

Monday 29 April 2019

How do I upload and download files to/from a server using express?

I would like to upload and download files to/from a given server running express and mongo in the back end. How would I achieve this?If there are any tutorials which could help, feel free to direct me to them if you think it's good material.

Submitted April 30, 2019 at 07:32AM by crabbiepatties1

Publishing on NPM Registry and GitHub, which Node version?

Let's say I wrote a NPM package in Node 12. I have a few questions about this process:Should I publish to NPM registry as Node 12? If I do, will users accidentally download it using npm install if their Node version is not 12?If I transpile my code (e.g. from Node 12 to Node 10) via TypeScript or Babel, what would happen?Do I publish both my Node 12 and Node 10 code to the NPM registry? How would users know which Node versions are available? How do they specify which Node version they want to download?How would users contribute to the codebase, if it is in Node 10? How would these changes done in Node 10 propagate upstream to my Node 12 codebase?​I am very confused about this compatibility and transpiling process. I suppose this confusion is true for all transpiled codebases, e.g. TypeScript -> JavaScript, or ESNext -> ES6 codebases. How do the developers specify or enforce compatible versions? How can the users download for their Node versions? And how can the community contribute back to transpiled codebases?

Submitted April 30, 2019 at 06:57AM by Roselia_Party

Pipey 1 is in alpha

Point-free programming in javascript has never been easier. Pipey 1.0.0-alpha.0 comes with an alternate, proxy-based, lodash-esque api to be an even better companion to functional composition in javascript. All that power inside a <700 bytes library.Example: https://twitter.com/phenax5/status/1122575469805621248Github: https://github.com/phenax/pipey

Submitted April 30, 2019 at 04:09AM by akshay-nair

How do I install nodejs from the downloaded file on Ubuntu?

This is probably an easy one but I am having trouble installing nodejs from the file that I download from the website. I tried running sudo apt-get install nodejs but I only got v10.15.2 . The one I downloaded from the website is version v10.15.3 but I don't know how to build it.

Submitted April 30, 2019 at 02:09AM by izak_t

Problem with pg-promise.

Don't know why empty result is error! Empty result from any DB is OK! I try to run many queries with Promise.all, but with any empty query get fail for all. Is any way to configure this lib for return empty as result not as error?Thanks a lot!

Submitted April 30, 2019 at 12:22AM by i_soshnikov

Node and SQL

I always worked with non relational databases and node. I’d like to use a relational database (SQL based). What’s the seamless way to integrate node and an SQL based database? I’m trying to understand what’s the most used with node.

Submitted April 29, 2019 at 11:27PM by pimpante

calling function with an empty parameter - what do you use null or undefined?

If there is a function foo(x, y, z) and you want to call it with empty parameter 'y', what is better/more used and why? :foo('lala', null, 2); //or foo('lala', undefined, 2); function foo(x, y, z) { if (x) console.log(x); if (y) console.log(y); if (z) console.log(z); }

Submitted April 29, 2019 at 10:52PM by making_bugs

Passwordless - Enable passwordless registration with SMS via AWS Lambda & AWS SNS

https://github.com/serverless-components/passwordless

Submitted April 29, 2019 at 05:01PM by austencollins

How to use non-loopback IP address in development for express/koa?

When developing in express or koa and I want to get the IP address (ctx.ip in koa) it gives me 127.0.0.1 because I'm accessing the site locally on localhost. Is there any way I can set up node or express/koa to not use loopback and use my "real" IP when accessing a certain site or port? I've got it running on http://somednsalias.development:3000 where the alias comes from a local dnsmasq server.

Submitted April 29, 2019 at 09:07PM by nowboarding

Why can't I add a property directly to req.session?

So, I have a POST route that adds properties to req.session like this:req.session.a = a;req.session.b = b;...But then I get this error, "Can't set headers after they are sent."Why is this? If I add something to req.body, it doesn't complain, but if I add something to req.session, I get that error, then I have to delete my cookie and restart the server.

Submitted April 29, 2019 at 09:12PM by Mobile_Monk

My first NPM Package

I've just made and published my own first NPM package!I'm a beginning web developer, while coding one of my personal projects I ran through an simple issue with Express and decided to make a NPM package out of the solution.I saw it as a great opportunity to learn to make and publish packages and as a way to contribute back to the our community.​The ProblemI was developing an Express website which had a lot of data within JSON files, each file had a list of objects, that would need to be served by Express in a HTML template.​Express provides a relatively easy ways to do templating, you can just set and install a templating engine as Handlebars and Pug to it.Although, I didn't want to install a template library just for the simple operation of injecting values.​What JSON-Pages (Yep, that's the name) does, is it automates the process of injecting JSON objects into a HTML template and serving them into an unique path in your server.All it needs to work is the path to a folder containing: JSON files and a HTML file. And optionally an unique key of each objThe use within my project looked like this:app.use(jsonPages(''))

Submitted April 29, 2019 at 09:15PM by Schapke

How does NPM create package.json files, filled out?

If you’ve ever used npm init, you’ve probably noticed that it fills out the information from the console questionnaire. I’m wondering, how it does this, and if there is any source code available, to tinker with?I’m trying to do something similar, where a user answers a few questions, and it automatically creates certain files, based off of a template I’ve put together, and any help would be awesome.

Submitted April 29, 2019 at 07:41PM by WebDevLikeNoOther

Understand how to approach designing queues in Node

https://www.coreycleary.me/understand-how-to-approach-designing-queues-in-node/

Submitted April 29, 2019 at 06:50PM by pmz

"Big Data" Engineering with Node.js

http://blog.jasonkim.ca/blog/2019/04/27/data-engineering-with-nodejs/

Submitted April 29, 2019 at 07:02PM by jsnk

changed hosting providers, nodemailer not working anymore

Hey guys,​so previously I had a contact us form that just sends me an email using nodemailer. I switch hosts and noticed it didn't work so I realized I still had my old host info etc.. I created a new email account under cPanel and the new hosting and adjusted my function but it doesn't seem to work. I've spent a couple of days and don't know what would cause it. I keep getting this e-mail, I verified sending an email to the account using my phone and it works, so I even verified the email settings and it matches my code config (port 465, hostname). I've tried diff combinations (port:587, secure:false) and nothing seems to work​This is the sample code:app.post('/contactsubmit',function (req, res) {let mailOpts, smtpTrans;smtpTrans = nodemailer.createTransport({host: 'server218.web-hosting.com',port: 465,secure:true,auth: {user: 'support@bubble-tech.ca',pass: 'dummypassword123'},tls: {// do not fail on invalid certsrejectUnauthorized: false}});mailOpts = {from: 'test@noreply.com',to: 'support@bubble-tech.ca',subject: 'test subject',text: 'please work'};smtpTrans.verify(function(error, success) {if (error) {console.log("verify error"+error);} else {console.log("Server is ready to take our messages");}});smtpTrans.sendMail(mailOpts, function (error, response) {if (error) {console.log(error);}else {res.render('contact-success');}});});

Submitted April 29, 2019 at 07:07PM by akash227

Node v12.1.0 (Current)

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

Submitted April 29, 2019 at 05:35PM by vzhou842

How we added a public API to our existing Node.js SaaS app

https://blog.checklyhq.com/how-we-added-a-public-api-to-our-saas/

Submitted April 29, 2019 at 05:02PM by Timnolet

Node v12.1.0 (Current)

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

Submitted April 29, 2019 at 05:06PM by dwaxe

An example multiplayer (.io) web game built with only Javascript

https://github.com/vzhou842/example-.io-game

Submitted April 29, 2019 at 05:31PM by vzhou842

Serverless Realtime Applications – Easily build websockets backends on AWS Lambda & AWS API Gateway Websockets

https://github.com/serverless-components/realtime-app

Submitted April 29, 2019 at 05:12PM by austencollins

Node.js v12 - New Features You Shouldn't Miss

https://blog.risingstack.com/node-js-12-new-features/

Submitted April 29, 2019 at 04:08PM by hfeeri

Querying subdocuments mongoose

How would I query a subdocument in mongoose? const userSchema = mongoose.Schema({ email: { type: String, required: true, unique: true, trim: true } sessions: [ { ip: { type: String }, token: { type: String }, browser: { type: String }, os: { type: String }, date: { type: Date } } ] });Let's say there a schema like this where I store the sessions of users and along with a token, if the user is accessing from same ip, browser and os, I give him the same token, if not I create a new token and supply him. In order to achieve that, I need to query a subdocument with the information I know but right now, I guess there isn't a method to do it?I could do,User.findOne({email: email, 'sessions.ip': ip, 'sessions.browser': browser, 'sessions.os': os}).then(user => {});That would just give me the user document but how would I give the user his ip until I get the specific subdocument?Should I just use filter or for..loop on the user document or is there a better way to do it? Thanks. (I know the process maybe flawed but right now I am just worried about querying the subdocuments)Found a solution, not yet 100% sure, but this works, User.findOne( { email }, { sessions: { $elemMatch: { ip: userAgent.ip, browser: userAgent.browser, os: userAgent.os } } } ) .then(user => { res.json({ user: user.sessions[0].token }); })

Submitted April 29, 2019 at 12:49PM by sum__sleples

Google is Implanting Node.js in Its New OS Fuchsia to Bring Deep JavaScript Support!

Google's new microkernel-based OS Fuchsia, a replacement of monolithic-kernel based OS Android, supports smartphones, tablets, PCs, cars, watches, traffic lights to almost all embedded devices. Node.js is being deeply implanted into it so that JavaScript apps can run here smoothly by default.News Link - https://www.androidpolice.com/2019/03/19/google-working-to-bring-javascript-app-support-to-fuschia/

Submitted April 29, 2019 at 12:06PM by Musfiq-Fahad-Amin

Announcing a new — experimental-modules in Node

https://medium.com/@nodejs/announcing-a-new-experimental-modules-1be8d2d6c2ff

Submitted April 29, 2019 at 10:09AM by stefanjudis

Send Images and Other Media via WhatsApp Using Node.js

https://www.youtube.com/watch?v=DNXwDrBb4PY&feature=youtu.be

Submitted April 29, 2019 at 09:06AM by stefanjudis

Easy authentication in GraphQL with Express and Apollo

https://ikbendirk.nl/posts/easy-authentication-in-graphql-with-express-and-apollo

Submitted April 29, 2019 at 08:07AM by harlampi

Why Use NodeJS | 10 Reasons To Select Node Web Development

https://aglowiditsolutions.com/blog/why-use-nodejs/

Submitted April 29, 2019 at 08:21AM by aglojane

Sunday 28 April 2019

How I used Mutation Testing to Improve my Code

https://medium.com/p/71c7fcf5174d

Submitted April 29, 2019 at 07:31AM by jsloverr

Node 12 - what are the new improvements and features?

https://www.angularminds.com/blog/article/node-12-what-are-the-new-improvements-and-features.html

Submitted April 29, 2019 at 06:32AM by EllaNicholls

Building an HTTP server on a Digital Ocean droplet. Should I run NodeJS with Apache, or use all NodeJS

Another way to ask this question: I know that NodeJS can be an HTTP server, but should it?Having a hard time finding definitive answers as to best practices. The goal is to host websites and an ExpressJS API.

Submitted April 29, 2019 at 12:39AM by IronOhki

Debug E11000 Errors in Mongoose

https://masteringjs.io/tutorials/mongoose/e11000-duplicate-key

Submitted April 28, 2019 at 09:29PM by code_barbarian

Created a library making time easier to compose with promises

https://github.com/gabeklein/good-timing

Submitted April 28, 2019 at 08:00PM by termtm

How does Node.js exit if it receives a SIGTERM and sockets are open?

As I understand it, Node waits for the event loop to empty (no more async code running) before it exits.But what if you have a connection to Mongo DB for example?Does Node just ignore this connection and exit anyway? What happens if you can't close it programatically because the async operations depend on it?

Submitted April 28, 2019 at 07:31PM by longyearbyen2

How to send post request with react server to express server with axios?

I have a client/react (port 3000) server and an express (port 3001) server. I am sending a post request with axiosaxios.post('http://localhost:3001/test', this.state.appointments); to the express serverrouter.post('/test', function(req, res) { console.log(req); res.send("Worked!!!"); }); I get this error when I do it:Access to XMLHttpRequest at 'http://localhost:3001/test' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Submitted April 28, 2019 at 05:17PM by AmirSaran

Nodejs how to get array of socketio sockets from redis adapter

I am currently using redis adapter in my socketio setup I want to be able to get an array of sockets from redis adapter so that I can check the session and only send data to the array with the correct account id I have tried the following code but returns an empty array any help?NET.getDashboardSockets = () => { return new Promise((resolve, reject) => { const sockets = []; NET._io.of("/dashboard").adapter.clients((err, clients) => { if (clients.length > 0 && err == null) { for (let i = 0; i < clients.length; i++) { const client = clients[i]; const socketData = NET._io.of("/dashboard").to(client) if (socketData != null) { sockets.push(socketData); } } } resolve(sockets); }); }) } NET.getDashboardSocketsWithId = (Account) => { return new Promise((resolve, reject) => { const retsockets = []; NET.getDashboardSockets().then(sockets => { for (let i = 0; i < sockets.length; i++) { const socket = sockets[i]; if (socket.handshake != null) { const acctId = socket.handshake.session.accountId; if (acctId != null) { if (acctId == Account.getId()) { retsockets.push(socket); } } } } resolve(retsockets); }) }) }

Submitted April 28, 2019 at 02:34PM by MrHid6

Learn Strapi (nodejs headless CMS)

https://www.youtube.com/watch?v=hisau__LM-o

Submitted April 28, 2019 at 01:56PM by EatAllTheGame

Node.js modules and the "use strict" directive

http://imaginativethinking.ca/what-the-heck-is-node-modules-strict-by-default/

Submitted April 28, 2019 at 02:02PM by brunokrebs

Please comment out libraries and packages you use for Back-end development.

Hey devs, please list out libraries and packages you used for your back-end projects.

Submitted April 28, 2019 at 02:15PM by Chawki_

How can I use two presets with Jest?

Im trying to set up ts-jest and @shelf/jest-mongodb for mongodb testing, but im not getting anywhere.

Submitted April 28, 2019 at 11:15AM by Kr7731

Photo collage application

Is node ( electron) a good choice for developing a photo collage application . Have plans of extending the application beyond collage making, in the future. Do you suggest to adopt electron for this ?

Submitted April 28, 2019 at 07:52AM by tettusud

Saturday 27 April 2019

async/await help

For context, This is a method in a class. I need it to display "first, second, third". I think my understanding of async/await is wrong because this shows "third, second, first". Can anyone help me out?async testing() {await setTimeout(() => {console.log('first')}, 1500);if(true) {await setTimeout(() => {console.log('second')}, 1000);}await setTimeout(() => {console.log('third')}, 500);

Submitted April 28, 2019 at 04:57AM by Stripestar

anything like wordpress that has a strong communjity but written in node?

I don't really feel like installing PHP just to get wordpress.

Submitted April 28, 2019 at 03:56AM by chovy

Stream read large XML File with node

Hi, I'm about to work on project where I have to handle large xml files (about ~80-100 MB). I need to read the file, parse it, pick the data that I need and write it to a mySQL database. Since thexml files are very large, the whole would take a long time or even not work if there is not enough memory to load the files. The solution should therefore probably be a stream. I have already googled but all npm packages seem to be no longer maintained, outdated or not well documented. Also, all the articles I have found on the subject are outdated. Can someone recommend a good tutorial or a good npm package for this problem?

Submitted April 27, 2019 at 11:23PM by xBlackShad0w

Webscraping in NodeJS Without a Headless Browser

https://www.youtube.com/watch?v=xpe__wVu1To&t

Submitted April 28, 2019 at 01:27AM by KayabaAkihikoBDO

Looking for smaller testing utilities

I am using tools such as Nyc, Mocha and Jest to do Node.js testing.The number of dependencies these tools install completely eclipse my regular non-dev tools.mocha's dependency tree has 115 nodesnyc's dependency tree has 170 nodesjest's dependency tree has 485 nodesThis seems to all be growing as these projects evolve.Generally when I add dependencies to my own projects, I try to find utilities that are low in complexity. I am usually willing to trade off a few features to reduce the total amount of code in my projects.This is not always possible though, but I thought I would give it a shot. Is anyone aware of 'good enough', simpler versions of testing utilities?

Submitted April 27, 2019 at 08:40PM by evertrooftop

Need help with a beginners issue

Hello,I can’t get the contentful connection up and running and this is what I have:I have a node script that makes the connection to contentful named connectcontentful.js in the data folder with this code:import * as contentful from 'contentful' const SPACE_ID = '123456' const ACCESS_TOKEN = 'ABCGDEFG' const contentclient = contentful.createClient({ space: SPACE_ID, accessToken: ACCESS_TOKEN }) export default contentclient Then I want to load that into my app.js with this code:var cc = require('./data/connectcontentful'); cc.contentclient.getEntry('3dImb5wbU7dD1qdllUgBY6') .then(function (entry) { // logs the entry metadata console.log(entry.sys) // logs all fields console.log(entry.fields) // logs the field with ID image console.log(entry.fields.image) }) When I run app.js I get this error:​×TypeError: Cannot read property 'getEntry' of undefined./src/App.jssrc/App.js:3 1 | var cc = require('./data/connectcontentful'); 2 |3 | cc.contentclient.getEntry('3dImb5wbU7dD1qdllUgBY6') 4 | .then(function (entry) { 5 | // logs the entry metadata 6 | console.log(entry.sys)View compiled__webpack_require__/Users/timloenders/Dropbox/co-own.it/app2/webpack/bootstrap:781 778 | }; 779 | 780 | // Execute the module function781 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId)); | ^ 782 | 783 | // Flag the module as loaded 784 | module.l = true;View compiledfn/Users/timloenders/Dropbox/co-own.it/app2/webpack/bootstrap:149 146 | ); 147 | hotCurrentParents = []; 148 | }149 | return webpack_require(request); | ^ 150 | }; 151 | var ObjectFactory = function ObjectFactory(name) { 152 | return {View compiledModule../src/index.jshttp://localhost:3000/static/js/main.chunk.js:129:62__webpack_require__/Users/timloenders/Dropbox/co-own.it/app2/webpack/bootstrap:781 778 | }; 779 | 780 | // Execute the module function781 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId)); | ^ 782 | 783 | // Flag the module as loaded 784 | module.l = true;View compiledfn/Users/timloenders/Dropbox/co-own.it/app2/webpack/bootstrap:149 146 | ); 147 | hotCurrentParents = []; 148 | }149 | return webpack_require(request); | ^ 150 | }; 151 | var ObjectFactory = function ObjectFactory(name) { 152 | return {View compiled0http://localhost:3000/static/js/main.chunk.js:257:18__webpack_require__/Users/timloenders/Dropbox/co-own.it/app2/webpack/bootstrap:781 778 | }; 779 | 780 | // Execute the module function781 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId)); | ^ 782 | 783 | // Flag the module as loaded 784 | module.l = true;View compiledcheckDeferredModules/Users/timloenders/Dropbox/co-own.it/app2/webpack/bootstrap:45 42 | } 43 | if(fulfilled) { 44 | deferredModules.splice(i--, 1);45 | result = webpack_require(webpack_require.s = deferredModule[0]); | ^ 46 | } 47 | } 48 | return result;View compiledArray.webpackJsonpCallback [as push]/Users/timloenders/Dropbox/co-own.it/app2/webpack/bootstrap:32 29 | deferredModules.push.apply(deferredModules, executeModules || []); 30 | 31 | // run deferred modules when all chunks ready32 | return checkDeferredModules(); | ^ 33 | }; 34 | function checkDeferredModules() { 35 | var result;View compiled(anonymous function)http://localhost:3000/static/js/main.chunk.js:1:57This screen is visible only in development. It will not appear if the app crashes in production.Open your browser’s developer console to further inspect this error.------​So probably I skip a step or something. Anyhow in Atom the “const contentclient” doesn’t color the contenclient orange like it should do with a const I would say.Sorry to bother with this beginners stuff, but I can’t get through this one.Thanks for any help!Tim

Submitted April 27, 2019 at 08:17PM by tlow001

Why is windows node binary about 62% the size of Linux and Mac binaries?

The Windows node binary is about 25MB; the Linux and Mac binaries are about 40MB. I'm curious, why the large discrepancy in file sizes?I'm asking this question purely out of curiosity; I do *not* have a filesize-related problem that I need to solve.I have a couple guesses:a) differences in the ELF and PE file formats.b) Some sort of compression.c) Windows guarantees a greater bulk of functionality in its core DLLs, whereas Mac and Linux are more unpredictable across OS versions and distros, so node needs to statically link more libraries❯ ls -al "$( which node )" ; ls -al "$( which node.exe )" -rwxr-xr-x 1 root root 43226968 Apr 23 14:23 /usr/local/bin/node -r-xr--r-- 1 abradley abradley 26774168 Apr 23 12:24 '/c/Program Files/nodejs/node.exe'

Submitted April 27, 2019 at 08:19PM by cspotcode

Are there any good resources to get into typeorm / mysql / express

Hello dear node ppl, or should i say NaNaNaNaNaNaNaNaNaNa?​But please don't get distracted, because i have a real lack of information, a real question, and maybe you can help me on this.I will have a some time to spare, saved some money and want to move forward in my developer career. After being the Frontend Guy for like 5 years with jQuery, Vanilla, ES6, Typescript, React, Vue, npm blabla, i decided it's time to became a "fullstack" developer.To become one, i need to learn to write REST APIS and/or GraphQL.I know hibernate is a thing and i understand the principles. I had i long look at typeorm and i think i should give it a try.Now to my question, and yes i already asked big brother, google and udemy. Where can i find a state-of-the art MMOC - i am willing to pay - that teaches me mySQL/Typeorm/Express. Is there something like this out there?I would be happy for every linked ressource.​Thanks for your time and happy coding.

Submitted April 27, 2019 at 07:40PM by paulqq

Express not applying css or scripts

I'm linking a css file to my express-handlebars file but I am getting this error:Refused to apply style from 'http://localhost:4000/cs366/style/draft.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.GET http://localhost:4000/cs366/JS/draft.js net::ERR_ABORTED 404 (Not Found)I have the static directory set, and my css and script files are being applied and loaded in home.handlebars, but not fantasyDraft.handlebarsMy file directoryproject |-- public | `-- style | |-- home.css | `-- draft.css |-- Fantasy | `-- fantasyRouting.js |-- views | |-- fantasyDraft.handlebars | `-- home.handlebars |-- app.js `-- connect.js App.jsconst express = require('express'); var exphbs = require('express-handlebars'); const db = require('./connect'); //connnect to db const path = require('path'); const app = express(); //middleware app.use(express.urlencoded({extended: false})); //static folder app.use(express.static(path.join(__dirname, '/public'))) //handlebars middleware app.engine('handlebars', exphbs({defaultLayout: null})); app.set('view engine', 'handlebars'); //home app.get('/cs366', (req, res) => { res.render('home'); }); //fantasy app.use('/cs366/fantasy/start', require('./fantasy/fantasyRouting')); fantasyRouting.JS - Handles the routes for a part of the application to avoid clutter in app.jsconst express = require('express'); const router = express.Router(); router.post('/', (req, res) => { players = [ { id: 1, name: 'Alex Johnson', position: 'p10', ovr: 60 }, { id: 2, name: 'Carl Erdman', position: 'p2', ovr: 76 }, { id: 3, name: 'Joe Enslin', position: 'p1', ovr: 29 } ] res.render('fantasyDraft', { players: players }); }); module.exports = router; fantasyDraft.handlebars

Drafting

Name OVR Postion
Name OVR Postion
home.handlebars

CS-366 Soccer

stuff



Submitted April 27, 2019 at 06:45PM by Ce-Jay

Are there drawbacks to “including” files you don't require in PUG?

I want to load a different mixin depending on what data the pug file gets passed. This requires me to store mixins as a variable. e.g.+#{slug}()where slug is the variable. This works well but (because dynamic mixins aren't possible) the drawback is I have to "include" all the pug files (even one's which are never required)include ./mixins/slug1include ./mixins/slug2include ./mixins/slug3etc ...Are there drawbacks to including loads of pug files you don't need? Or is it the case where if you just "include", but never actually call the file then it's all ok? Thanks for any help :)

Submitted April 27, 2019 at 06:13PM by harrydry

Free, Privacy-focused Analytics service I built in NodeJS (Feedback Appreciated)

https://paperclip.live?src=rnode

Submitted April 27, 2019 at 05:23PM by 63-bit

Loopback + MongoDB Atlas

Anyone know how to correctly connect mongodb atlas to a loopback application? I can’t seem to get loopback to connect through the loopback-mongodb-connector with atlas.

Submitted April 27, 2019 at 03:26PM by kevinisathought

Is there a way to detect if a remote app code has been altered?

Hi,I developed an nodeja app that receives text data (unpredictable) via websocket from remote nodejs apps (agents).I'd like to make agents available to people so they can install and run their own agents contributing to data collection.But I need a way to verify that agents have not been modified so I can trust data I receive. Any idea about that?Thank you!

Submitted April 27, 2019 at 01:35PM by Ciao121

Etna - An opinionated API boilerplate built with node/typescript

Introducing - Etna 🌋An opinionated API Boilerplate project built with Node.js, TypeScript , objectionjs, Knexjs - Inspired by and built on top of Matterhorn 🏔️Read my blog article for more info⏱ Runtime: Node.js🖥 API Framework: Fastify🔏 Type System: TypeScript📎 ORM: objectionjs❔ QueryBuilder: Knexjs🗃️ Databases: RDMS (Relational database management system)🎭 Test Runner: Jest👕 Linter: ESLintCheck out the repo @github - https://github.com/DasithKuruppu/etna

Submitted April 27, 2019 at 01:04PM by dasithkuruppu

Reddit Bot with NodeJs & Puppeteer ( Part 2 ) - Posting on Subreddits

https://www.youtube.com/watch?v=L-ksqOGcfUM

Submitted April 27, 2019 at 10:11AM by GrohsFabian

Friday 26 April 2019

nginx, firewall, and node setup question

I have a linux VPS running nginx as a reverse proxy to my node server. On my VPS, I have node server running on localhost:9999.My nginx is listening on port 80, where if hostname is my website url or ip address, redirect it to https. The server block listening on 443, specifically the server_name variable, has my webserver's IP address on it.If I go to my webserver's IP address port:9999, it loads my website. Is this suppose to happen? Am I suppose to block port 9999 from public access and only accessible by my nginx server?

Submitted April 27, 2019 at 07:15AM by eggtart_prince

How to mock a method that accepts no arguments and its supposed to work normally in 1 test, and supposed to throw an error in another test

I'm trying to get 100% coverage on my AWS project but I don't know how to mock methods that don't accept arguments AND are supposed to pass a test that makes them work properly(return values) and another test that makes them throw an error. I can't change the tech I am using so please try to help me with the things I am using right now.I am using Nodejs, Typescript, Mocha, Chai, nyc and mock-require for mocking. (The way mock-require works is that when you require something, in this case "aws-sdk", it replaces all methods of it with my own)It's an AWS project so I am working with AWS methodsHere is the function and method, I am mocking describeAutoScalingGroups()​​export async function suspendASGroups() { const autoscaling = new AWS.AutoScaling(); const asgGroups = await autoscaling.describeAutoScalingGroups().promise(); if (!asgGroups.AutoScalingGroups) { throw new Error("describeAutoScalingGroups inside of suspendAGSGroups didn't return any groups"); } ​This is the TEST that is supposed to fail(Above this there is a test of the same function which will return regular values)it('Should throw an error, should fail', async () => { try { let result = await awsFunctions.resumeAGSGroups(); } catch (e) { assert.isTrue( e.name == 'Error' && e.message == "describeAutoScalingGroups in resumeAGSGroups didn't return any groups", 'describeAutoScalingGroups in resumeAGSGroups didnt have the proper error message' ); } }); And here is the mock codeclass AutoScaling { constructor() { console.log('mock constructor called'); } public describeAutoScalingGroups() { const data = (): AWS.AutoScaling.Types.AutoScalingGroupsType => { return { // return some stuff }; return { promise: data }; } } I expect to be able to pass both tests, the one that expects a regular value and one that expects it to throw an errorhere is a picture of the coverage: https://i.imgur.com/D6GX0tf.pngI expect that red part to be gone :)Thank you

Submitted April 27, 2019 at 07:38AM by khazha88

How to get node.js code working in an electron app?

Hello,I'm a complete beginner with javascript, node, and electron, however I'm making an app using these, and part of the app involves me using the yelp api. To do this, I have to include the lineconst yelp = require('yelp-fusion'); And the rest of the code is querying the api and printing the results. When I run this code directly through node, it works fine, however when I add this file to my electron project, which is used by an html file, I get the error:Uncaught Error: Module name "yelp-fusion" has not been loaded yet for context: _. Use require([])I tried following the instructions at https://requirejs.org/docs/errors.html#notloaded but i was unable to solve the issue, and to be honest I'm not understanding why this is an issue, since node has no problems with it. Perhaps I am just using electron incorrectly?

Submitted April 27, 2019 at 04:54AM by brett96

How to make sure each streams write go in right order.

Hi, here is the code of my function simplified:function writePage(request,response){ // Write opening Tags response.write(""); writeHead(request,response); writeBody(request, response); //Write closing tags response.write(""); } function writeHead(request, response){ config.baseHeadElements.forEach((element)=>{response.write(element)}); config.pages[request.url].headElements.forEach((element)=>{response.write(element)}); } function writeBody(request, response){ response.write(""); //this is mostly the part where trouble happens: config.pages[request.url].includeInBody.forEach((path)=>{ fs.createReadStream(__dirname + path).pipe(response, {end: false}); }); response.write(""); } How it is right now, each element of the arrays end up in the page, but not always in the right order. How can I ensure that I am only writing in response one thing at at time, in the good order?

Submitted April 27, 2019 at 02:23AM by tonystark027

The #GridDB #Nodejs client has been updated. Download and update through GitHub

https://twitter.com/GridDBCommunity/status/1121883909069783041

Submitted April 26, 2019 at 10:51PM by IllegalThoughts

Serving a directory listing with Restify?

Hey I can't find any docs about this. It seems to be possible with express using the serve-index package but I'm not sure how to do this with Restify, does anyone have an idea?

Submitted April 26, 2019 at 10:55PM by moving808s

NestJS, let services handle the complex stuff?

I just started working with NestJS and in the documentation I read something about services. For as far I understand controllers are used to catch HTTP requests and call a method from a service that is injected into the controller to handle the more complex stuff.This seems unnecessary to me, why should I call a seperate function from another class if I could manage to do that complex stuff just as good as in the controller method itself? I could see why services would be useful. for example if multiple controllers need to use the same logic.

Submitted April 26, 2019 at 07:55PM by Beurni

Mastering JavaScript: Setting Request Headers with Axios

http://masteringjs.io/tutorials/axios/headers

Submitted April 26, 2019 at 06:37PM by code_barbarian

Is it possible to import a JSON file based on the path in the .env?

I'm using ES6 modules and I'm loading the data like this:import data from './somefolder/config';This works, but when I try to do something like this:import data from `${process.env.JSON_PATH}`Naturally, this doesn't work at all. Are there any workarounds here?Basically I have two config.json files, one for development and one for production and I'd like to load it based on this. Sure, I could check if the .env is production or not and based on that load the data, but I wanted to make it more config-oriented.Any ideas?

Submitted April 26, 2019 at 05:38PM by JavascriptFanboy

What's New in Node.js 12: ESM Imports

http://thecodebarbarian.com/nodejs-12-imports.html

Submitted April 26, 2019 at 04:36PM by code_barbarian

Strapi beginner question

Im starting out with learning node.js and i use strapi to build apis. It's possible to create a backend for a booking system with strapi? For the beginning the app will have a section where you can choose a start date and a ending date. After the user passed down the dates i would like to display the rooms that are available in that period of time.Thanks for the help

Submitted April 26, 2019 at 03:36PM by echolko

Google’s Web Security Researcher Krzysztof Kotowicz: Insecure Coding Is the Default

https://medium.com/@amsterdamjs/googles-web-security-researcher-krzysztof-kotowicz-insecure-coding-is-the-default-413a144ce4cb

Submitted April 26, 2019 at 01:31PM by FrontendNation

Multi-gateway payment processing module

https://github.com/continuous-software/42-cent

Submitted April 26, 2019 at 01:33PM by javitury

What alternatives are there to Passport for user logins?

Are there any that are simpler? Which do you like?This is the Passport I'm talking about: https://www.npmjs.com/package/passport

Submitted April 26, 2019 at 01:19PM by WarAndGeese

jipe - A bash utility to add JavaScript code to a pipe

https://github.com/drewhodson/jipe

Submitted April 26, 2019 at 01:13PM by drewhodson

What are the differences between the express-handlebars, express-hbs and hbs modules,

I'm trying to use Handlebars with Express, and I found the modules express-handlebars, express-hbs and hbs which all seem to work similarly. What are the main differences between them that I should be aware of, given that I need to able to use layouts and partials?

Submitted April 26, 2019 at 11:53AM by rayhan666

What else should I learn to be a Back-End Dev?

Hello, devs, I learn Express, mongoose EJS, and what else should I learn to become a Back-End dev?

Submitted April 26, 2019 at 09:37AM by Chawki_

Thursday 25 April 2019

Global HTTP/HTTPS proxy for Node.js v12+

https://github.com/gajus/global-agent

Submitted April 26, 2019 at 07:30AM by gajus0

mazebattles.com / race to solve mazes (built with node.js + socket.io)

http://www.mazebattles.com/

Submitted April 26, 2019 at 06:01AM by arcialga

nTennah's latest Node.js newsletter

https://www.ntennah.com/issue/nodenTennah is a new service that brings the important and influential content and conversations from a variety of sources into a single page to make it easier for developers to stay informed on topics that are important to them.This week's entries include:Introducing Node.js 12You should never ever run directly against Node.js in production. MaybeDeno: a better Node.jsWant to add recurring payments to your site? Here's an easy, 3-part guide to setting up Stripe subscriptions with Node.jsLeaflet – social media platform built with Node.js and MongoDBAsk HN: Why All the Hate for NPM?How do I run an await function after 3 secondsStripe charge not going throughPlease let me know what you think of the service and any way I can improve it.Thanks!

Submitted April 26, 2019 at 03:56AM by ntennah

I posted awhile ago, and I wanted to thank you all.

Awhile ago, I posted about a little project I was working on in Node.js called Voyager. I wanted to create a file manager built in Node.js and Electron that could work across all platforms the same way with minimal code modification. I made a final commit today and I went so far into it I thought I'd post it here too.​"This is just finalizing any tweaks. My deadline is approaching and I have a lot more to do on the non-coding side. It's time I close this chapter of Voyager and move on to a new base for the summer. Folks, I don't know if I'll be back soon or not. I have a new job coming up over the horizon and a lot of college prep to do as well. I will do what I can to do Voyager right the second time 'round. But, for now, I'm leaving behind the old platform and searching for a new one. It might be Node.js, it might not. It will most likely not be Qt, and probably not any x86 😂. All I can say for now is that I want to come back here. I do. The last month of development has taught me a lot about the commitment and the help you need to get a project through the pipe. And the funny thing is, the pipe never actually ends. Life and family and friends and users just add more to the end of the pipe. And that's okay. The goal is to get as close to the end as you can so maybe you can take a rest and say, "Huh. Look at that. I did that. That was pretty cool," and then immediately get back to it. So if you commented or starred or even so much glanced at Voyager, thanks. That's why I want to do this. I want people to see what I can build and what I can do. Moving forward, I want to keep the core of the project alive. And maybe, just maybe, someday Voyager will actually get to blast off. 🚀"​If you want to check out Voyager and build it for yourself, head over to my GitHub.

Submitted April 26, 2019 at 12:37AM by TotalChris

Node Express Redirect Server - Array filter vs Mongo Query

Hi there - I am setting up a dockerized node server to handle redirects for a decommissioned domain, so simply takes the URL path and perhaps matches it with regex against a list of urls with partly matching paths on a new domain. The volume of the list could range from about 4K to 50K. Still working it out but there's very little resources beyond this simple server to handle this. I'm wondering though in Node and JS in general at what point does a Mongo Query actually make performance better if at all against simple arrays of url strings like this. I'm trying to figure out if I can just load list one and list two, parse the request a bit, and filter or regex match it from the items in the second list to avoid a second container for Mongo, or if this might all fall apart without using a proper DB. Considered maybe redis could help but haven't used it yet.

Submitted April 25, 2019 at 11:06PM by charmgame

Reddit Bot with NodeJs and Puppeteer

https://www.youtube.com/watch?v=nW6lT-CzdVs

Submitted April 25, 2019 at 07:51PM by GrohsFabian

Set a netlify function as webhook to trigger firebase new signup

I use firebase to authenticate users I know I can use firebase cloud functions to trigger new signup, but I wanna use netlify functions instead. Is there is any way to do that?

Submitted April 25, 2019 at 05:56PM by 22mahmoud_

PLEASE: Share your Express.js project file architecture ( screenshot )

Because I don't have any idea,

Submitted April 25, 2019 at 03:32PM by Chawki_

Limiting concurrent operations in JavaScript

https://medium.freecodecamp.org/how-to-limit-concurrent-operations-in-javascript-b57d7b80d573

Submitted April 25, 2019 at 11:08AM by fagnerbrack

Avoid ugly If/else blocks & make your code modular with Strategy

https://itnext.io/avoid-ugly-if-else-blocks-make-your-code-modular-with-strategy-1c3364b2f920?source=friends_link&sk=13e98785051e3b70e7d3d153bb5bb046

Submitted April 25, 2019 at 07:25AM by jsloverr

Just messing around with my MIDI controller and Node.js

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

Submitted April 25, 2019 at 06:43AM by matheusmk3

Wednesday 24 April 2019

[Hiring] Sr. Node Developer- REMOTE

​Clevertech is looking for a Senior Node Engineer to join our global team. This role has implementation and troubleshooting responsibilities including multiple database interactions including MS SQL, Postgres, ReThinkDB, Redis, as well as Queueing interactions. Clevertech looks for craftsmen developers who take ownership of their code.You can deliver quickly while being clever to avoid missteps. You have an effective positive attitude that shines as you show you care about client and colleague concerns. You are always learning and are a transparent communicator even when it is challenging. You thrive on challenging yourself daily and seek to surround yourself with like minded individuals.REQUIREMENTSB.S. in Computer Science or equivalent experience followed by 5+ years experience in a senior developer or architect role; ideally, you have delivered business critical software to large enterprisesProgramming skills– You are comfortable writing code in multiple languages, confident in choosing the right strongly or dynamically typed language for the job. Preferred language familiarity: NodeJS, SQLDatabase skills – You understand the use cases for relational and non-relational data, you’ve implemented code against several different database platforms.Development experience - Web Applications, Service Oriented Architecture and Micro-Services.Knowledge of micro-services networking, load balancing, and service discovery concepts and technologies.Conduct code walk-throughs, peer reviews, and produce technical documentation.Bachelor’s Degree in Computer Science/Engineering or equivalent years of hands-on coding experience.Strong communicator and fluent in English with excellent written and verbal communication skills.Who We AreClevertech is a leading consultancy that is on a mission to build transformational digital solutions for the world’s most innovative organizations. Enterprise companies turn to Clevertech to help them launch innovative digital products that interact with hundreds of millions of customers, transactions and data points. By partnering with Clevertech these companies are propelling forward and changing their industries, business models and more.The problems we solve every day are real and require creativity, grit and determination. We are building a culture that challenges norms while fostering experimentation and personal growth. We are hiring team members who are passionate and energized by the vision of empowering our customers in a complex industry through technology, data and a deep understanding of client concerns. In order to grasp the scale of problems we face, ideally you have some exposure to Logistics, FinTech, Transportation, Insurance, Media or other complex multifactor industries.Our BenefitsWe know that people do their best work when they’re taken care of. So we make sure to offer great benefits.Competitive Vacation PackageAnnual Financial Allowance for YOUR developmentFlexible Family LeaveClevertech Gives Back ProgramClevertech U (Leadership Program, Habit Building, New Skills Training)Clevertech SwagStrong Clevertech CommunityHow We WorkWhy do people join Clevertech? To make an impact. To grow themselves. To be surrounded by developers who they can learn from. We are truly excited to be creating waves in an industry under transformation.True innovation comes from an exchange of knowledge across all of our teams. To put people on the path for success, we nurture a culture built on trust, collaboration, and personal growth. You will work in small feature-based cross-functional teams and be empowered to take ownership.We make a point of constantly evolving our experience and skills. We value diverse perspectives and fostering personal growth by challenging everyone to push beyond our comfort level and try something new.The result? We produce meaningful workGetting HiredWe hire people from a variety of backgrounds who are respectful, collaborative, and introspective. Members of the tech team, for example, come from diverse backgrounds having worked as copy editors, graphic designers, and photographers prior to joining Clevertech.Our hiring process focuses not only on your skills but also on your professional and personal ambitions. We want to get to know you. We put a lot of thought into the interview process in order to get a holistic understanding of you while being mindful of your time. You will solve problems derived from the work we do on a daily basis followed by thoughtful discussions around potential fit. Whatever the outcome, we want you to have a great candidate experience.Clevertech Culture VideoAPPLY FOR THIS POSITION

Submitted April 25, 2019 at 02:21AM by cleveramy

Hello.. creating a chatbot for twitch.. need some assistance..

Trying to make it where ppl can type !replay and it'll simulate a keypress to the system which will trigger a source in OBS... I've tried kbm-robot and node key sender from npm but they seem to only seem to work in a web browser, I need to interact with OBS.. any ideas?Thank you

Submitted April 24, 2019 at 11:13PM by TTVCoachSouz

How to connect Elasticsearch to my MySQL DB to make a search engine ?

I have a bioinformatics DB in which I have table of different molecule compounds (over 10,000 entries). I want to create a search bar where as I type in the name of the molecule, it comes up with results of cell_plates where these molecule compounds are stored (and this information is stored in different columns alongside molecule name in the same table).I was reading a lot of resources online, but couldnt find one on how to basically send my data from MySQL DB to Elasticsearch.Alternatively, could I just send a search query parameter to my SQL query that accomplishes the same task Elasticsearch would do, or is that an inefficient way to go about this?

Submitted April 24, 2019 at 09:25PM by yungspartan0082

Receive SMS Messages with Node-RED

https://www.nexmo.com/blog/2019/04/24/receive-sms-messages-node-red-dr/If you'd like to take it a step further, check out this flow for receiving concatenated SMS from Nexmo

Submitted April 24, 2019 at 08:58PM by juliabiro

Bunch of Development books with Node js are being on huge discount

Check them here : https://twitter.com/MAssortment/status/1121115372713840641

Submitted April 24, 2019 at 07:23PM by HildaDavidson

Can you trust emails from Google and Facebook OAuth?

I am building OAuth into my express app. When a user authenticates with Facebook or Google and I use that token to call eitherfb.api('me', { fields: ['id', 'first_name', 'last_name', 'email', 'cover'], access_token: accessToken}orplus.people.get({ userId: 'me', auth: self._client}Can I safely assume that the email Facebook or Google hands back to me is verified? I have read conflicting answers on this online. Some stack overflows say "Yes, Facebook only provides verified emails" and I have other people saying "don't trust anything".Normally it is not a big deal, but I can't create a user account until I know the email is verified. Being able to somewhat trust Google/FB to have done that cuts down on the sign-up friction a ton.What are your thoughts?

Submitted April 24, 2019 at 07:14PM by billymeetssloth

A JavaScript Package Registry funded, developed and maintained by the community, for the community

https://open-registry.dev/

Submitted April 24, 2019 at 06:31PM by victorbjelkholm

Node crashing often on my MacBook, but I don't know what is using node

Simple http2 server from NodeJS Official Docs not working for me

Hello Node Community,I came here as a refuge as I do not know any better NodeJS forums for asking questions. I hope I am in the right place. I am trying to learn NodeJS 10 LTS and while I was browsing the official documentation to try http2 server functionality I received errors in postman. I have posted in StackOverflow and have not yet received sufficient help. If you have a simple http2 server setup example/tutorial with Node 10 or later, kindly provide.https://stackoverflow.com/questions/55828540/simple-http2-nodejs-server-from-official-docs-postman-not-working/55829241?noredirect=1#comment98323499_55829241

Submitted April 24, 2019 at 01:03PM by tommy737

Google Cloud Key Management Service to sign JSON Web Tokens

crosspost from: (https://www.reddit.com/r/googlecloud/comments/bgtnv3/google_cloud_key_management_service_to_sign_json/)_Hey guys. Greetings from India!​First of all I tried the solution at: Using Google Cloud Key Management Service to sign JSON Web Tokens But it doesn't work.​Creating signature:​const TimeStamp = Math.floor(new Date().getTime() / 1000) let body = base64url( JSON.stringify({ alg: 'RS256', typ: 'JWT' }) ) body += '.' body += base64url( JSON.stringify({ iss: 'some-iss', aud: 'some-aud', iat: TimeStamp, exp: TimeStamp + parseInt(process.env.TOKEN_EXPIRY, 10) }) ) const hashedMessage = crypto .createHash('sha256') .update(body) .digest('base64') const digest = { sha256: hashedMessage } const [signatureObj] = await client .asymmetricSign({ name, digest }) .catch(console.error) const signature = base64url(signatureObj.signature) const token = `${body}.${signature}` ​Then verifying:const[publicKeyObject] = await client.getPublicKey({ name }).catch(console.error) const publicKey = publicKeyObject.pem const verify = crypto.createVerify('sha256') verify.write(body) verify.end() verify.verify(publicKey, base64url.decode(signature), 'base64') ​I'm not able to figure what is wrong with the code. Thanks!

Submitted April 24, 2019 at 01:04PM by Typical_Button_1

securing protected routes with JsonWebToken

how to check authorization of a protected route before accessing it. I can manage to visit my protected route by using loginID and password. But when I try localhost:/profile, i can able to view it. So can i check authorization of these routes.? Thank you.

Submitted April 24, 2019 at 09:12AM by chinni-reddy

How to Send a WhatsApp Message with JavaScript and Node.js

https://www.youtube.com/watch?v=PxphXQmtHLo&feature=youtu.be

Submitted April 24, 2019 at 07:24AM by stefanjudis

Tuesday 23 April 2019

Running node.js on remote server/Docker. How to use IDE?

Hi everyone,Trying to build my own internal home site for tracking bills, and a whole heap of other stuff for my family and I., thinking this would be a fun way to learn javascript and node. (My experience level with html, php, sql and css are very limited now compared to 11 years ago)As the title states, I would prefer to run my code on a remote server, and/or docker, use an IDE to connect to either and run scripts. I currently have visual basic code installed.Can anyone recommend how I can achieve this or advise otherwise?

Submitted April 24, 2019 at 04:28AM by kr3ate

Node, Express, React.js, Graphql and MongoDB CRUD Web Application

https://www.djamware.com/post/5cbd1e9a80aca754f7a9d1f2/node-express-reactjs-graphql-and-mongodb-crud-web-application

Submitted April 24, 2019 at 03:49AM by didinj

Is it common practice to set NODE_ENV in your profile (bash profile etc)?

titleassuming posix here

Submitted April 23, 2019 at 11:40PM by lowIQanon

web-ext : How do I deal with deprecated/removed packages?

Following firefox Addon tutorial, it says to use web-ext . I can't install it.I tried:$ npm install --global web-ext errors:npm WARN deprecated js-select@0.6.0: Package no longer supported. Contact support@npmjs.com for more info. npm WARN deprecated circular-json@0.3.3: CircularJSON is in maintenance only, flatted is its successor. npm WARN deprecated nomnom@1.8.1: Package no longer supported. Contact support@npmjs.com for more info. C:\Users\name\AppData\Roaming\npm\web-ext -> C:\Users\name\AppData\Roaming\npm\node_modules\web-ext\bin\web-ext C:\Users\name\AppData\Roaming\npm `-- web-ext@3.0.0 npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.0.1 (node_modules\web-ext\node_modules\addons-linter\node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform ... etc ... My versions:$ node --version && npm --version v7.0.0 3.10.8 I'm not sure where to go?Update node? I'm finding it says to use nvmSo, install nvm? It doesn't appear to be in the bin: /jodejs/use older version of the libraries?

Submitted April 23, 2019 at 09:08PM by MonkeyNin

Need Advice (Noob): The wild world of Node & ORMs

TL;DR: Frontend JS Developer wanting to build full stack web apps. Fairly new at backend. Want to build a coupon based website(very similar not exact). Tried Learning Django Rest framework, it was too much abstraction. Started learning node. Most tutorials use MongoDB/Mongoose. Need SQL but struggling choosing an ORM with Node. Tried Sequelize, Knex.js, Objection.js and been back and forth with all. Need help choosing one with great concern about data security (sqli, validation, serialization etc.). Knex.js by itself seems intuitive but not sure if it leaves me open to a lot of data breaches considering my limited SQL experience.I have a goal of wanting to build a web application that will be very similar to a coupon styled website (business owners post coupons, consumers claim coupons. Lots of different categories). I have been teaching myself Javascript/React for about 7 months so i have front-end knowledge covered for the most part. I finally ventured into backend as it was always my ultimate goal to have full stack knowledge to create online businesses/web apps.Initially started learning python and got into Django for its rest framework (Heard it was the best ORM by far). It was nice and robust but learning a whole other language was very daunting for me and all the abstraction of Django made it even more overwhelming. My fundamentals in JS are far superior to that of Python so i said i would just go with Node.js.Started taking a node.js tutorial which has been great, but unfortunately as you may know most tutorials use MongoDB (which i hate) and Mongoose. Since most of the ideas i have for web apps will have relational data, that was a dealbreaker for me.Thus leads me to the problem that seems common (based on reddit searches) with node, which are ORMs.I have looked at Sequelize, node-postgres, knex.js and Objection.js. I am struggling with choosing one, as based on my limited knowledge, all have their pros and cons.Its so frustrating as a noob as i have banged my head against the wall for the past 3 days moving from Sequelize to Knex.js to Knex.js with Objection.js back to Sequelize and doing it all over again.I like knex.js and it seems the most intuitive to me but i worry about security such as SQLi (very naive on this part of it). Does knex.js leave me to many security concerns?I see many advise to use Knex.js with Objection.js. However, there are hardly any tutorials to my knowledge (video or written) to follow and understand how they work with each other.Sequelize gives me the beauty of having a lot of tutorials to look at but the level of abstraction scares me.So with all that being said, what is my best course of action with my proposed web app that i would be building, taking into consideration data security (validation, serialization etc.). I have been stuck on this for a while and i just need some clarity on this.thanks in advance.

Submitted April 23, 2019 at 07:27PM by RSpringer242

Announcing a new --experimental-modules

https://medium.com/@nodejs/announcing-a-new-experimental-modules-1be8d2d6c2ff

Submitted April 23, 2019 at 08:02PM by NathanSMB

Does it make sense to use http2 behind a reverse proxy with http/2?

Say I have nginx with http/2 in front of my app instances. Would rewriting the app to use http2.createServer provide any performance benefits in communication between nginx and app server?

Submitted April 23, 2019 at 06:51PM by joocyfrooty

Introducing nTennah, a service to help you keep up to date on the latest articles and conversations

Hello all,I've been working on a service that helps keep you informed on the latest articles and conversations on topics and conversations that are important to you.The goal of the service is to bring to you the most important and influential content from a variety of sources by looking at the conversation and activity surrounding it, as well as the author's authority on the subject matter. These are published in a weekly newsletter that is available online, or you can subscribe and receive it as an email.While it's not entirely finished, I would really appreciate any suggestions and feedback to help make the service better.There is currently content from Medium, Reddit, HackerNews and StackOverflow; and working on providing more content. Up next is YouTube, and Github is a high priority as soon as I figure out how do it ;)There are newsletters for React, Node.js, and Angular currently, and plans to create a lot more.Please visit the site and let me know what you think!https://www.ntennah.com/

Submitted April 23, 2019 at 07:00PM by ntennah

Node v12.0.0 (Current)

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

Submitted April 23, 2019 at 07:17PM by dwaxe

Node 12 Features and Updates

https://levelup.gitconnected.com/whats-new-in-node-12-e00111ffb83f?source=friends_link&sk=09acce37e374841c877cbea34697c468

Submitted April 23, 2019 at 06:37PM by treyhuffine

Watch "Getting started with node.js on Google Cloud Functions - console & gcloud cli" on YouTube

https://youtu.be/MgivoBkvS5o

Submitted April 23, 2019 at 06:07PM by pmz

What's New in Node 12

https://medium.com/p/whats-new-in-node-12-e00111ffb83f

Submitted April 23, 2019 at 04:55PM by treyhuffine

Coding Help: Pausing one child process when another is running

Hey guys,​I am having trouble trying to "kill" a constantly running child process (let's call it Child Process 1) at the start of another (Child Process 2). Once Child process 2 is complete, I would like Child process 1 to start back up again. I was thinking of adding a while loop to the code below, but did not know how to go about doing it properly.​var exec = require("child_process").exec; const execFile = require('child_process').exec; //Activates Child Process 1 on Startup const child = execFile('/path/executable1', function (error, stdout, stderr) { if (error) { throw error; return; } }); if (message === '!exec') { execFile.kill(); // Trying to kill Child Process 1 here, maybe add while loop instead? var process = exec('/path/executable2', (error, stdout, stderr) => { //activates Child Process 2 if (error) { console.error(`exec error: ${error}`); return; } console.log(\`stdout: ${stdout}\`); console.log(`stderr: ${stderr}`); }); }); As of now Child Process 1 activates on startup, Child Process 2 activates on !exec, but Child process 1 is also still running. Any advice?

Submitted April 23, 2019 at 05:01PM by Mketcha3

DIY System Monitoring, Part 2: NodeJS Server

The second part of a three part series on building a simple server-monitoring app.Uses python, mongodb, nodejs, and chartjs.DIY System Monitoring, Part 2

Submitted April 23, 2019 at 05:14PM by tiarno

Import statements finally coming to nodejs

https://medium.com/@nodejs/announcing-a-new-experimental-modules-1be8d2d6c2ff

Submitted April 23, 2019 at 05:33PM by alpha-201

Introducing Node.js 12

https://medium.com/@nodejs/introducing-node-js-12-76c41a1b3f3f

Submitted April 23, 2019 at 05:41PM by vzhou842

Deno: a better Node.js

From the created of Node.js Ryan Dahl is creating Deno in hopes of fixing a lot of the problems inherent in Node.js. Deno was built on top of Rust, was heavily influenced by Go, and has built in TypeScript support.I'm stoked to built with this tech....Webpage: https://deno.land/Source Code: https://github.com/denoland/denoTalk by Ryan Dahl: https://www.youtube.com/watch?v=z6JRlx5NC9E

Submitted April 23, 2019 at 03:49PM by mick-io

ELI5: npm-registry

Hello,while reading the thread over at /r/javascript about the NPM layoffs followed attempt to unionize, according to complaints, there was discussion about alternatives about npm hosting and someone mentioned yarn.I always thought yarn was "just" a new CLI program to access (by default) the npm repositories, like apt-get and aptitude for Debian repositories.But then someone posted a link to https://registry.yarnpkg.com/ and I got confused what registries are and how they work.I looked up the documentation for npm-registry, which says:To resolve packages by name and version, npm talks to a registry website that implements the CommonJS Package Registry specification for reading package info.But how do you resolve packages from something like the https://registry.yarnpkg.com/? It looks more like a stats counter for me.I found an 11 month old Hacker News submission Yarn registry was down, with comments that it's just a CNAME for https://registry.npmjs.org/, even though looking at it's content, both files differ slightly. But how can they both link to the npm repository, there isn't any npm URL - something like "repository": "npmjs.com" inside the yarn registry JSON file?​So, can anyone explain to me what a registry (in this case) is, and how >npm i babel-core or $ yarn add babel can figure out from those files how to find the URL to download the appropriate file?

Submitted April 23, 2019 at 03:28PM by 0xnoob

Question

I have a question if you want the bot to edit the message you need the mesage IDbut how does the bot need to get the ID

Submitted April 23, 2019 at 02:24PM by RedSlimeySlime

How to avoid race condition with Async/Await Database operations ?

Hello, there.​Image the following scenario: Request "A" asks for a item in a list and its status is set to "false" on a MongoDB instance. In the same time, a request "B" arrives to Node.js and asks for a item and, like request "A", the item status is set to "false" too. The question is: How to avoid request "A" and "B" of ask for the same item in the list? I know that Node.js is single threaded, but if these database operations were executed without Async/Await something can goes wrong due to race condition, right ?

Submitted April 23, 2019 at 01:05PM by giocruz

Server Side State Management Recommendations?

Hi all,​Building a IP based control system based off of Node (AV, home automation, etc.) Aside from running the core program, Node will also serve the system control GUI as a web app via Express. So far this is all well and good and I can send and receive commands between Node and GUI via a websocket.​This issue now is I want to have multiple instances of the GUI that all sync together with the exception of things like page flips. Think having a touch panel in different rooms, someone using an app on their phone, etc. I have an old pseudo state management system I made for testing WebRTC, but it would need a lot extending and reworking to use.​Are there any more standardized (and robust) ways to handle syncing state across multiple web app instances in Node?

Submitted April 23, 2019 at 01:12PM by maudiosound

NodeJS Port Scanner - Requesting Help!

Hey All,​Just need some help with this port scanner that im mucking around with.I have put it up on github if someone can let me know where i have gone wrong.​Here is a dump of the code:​var net = require('net'); function checkHost(host, callback) { for (port = 1; port <= 10000; port++) { (function(){ portCheck(host, port, callback)})(); } } function portCheck(host, port, callback) { var socket = new net.Socket(), status = null; socket.on('connect', function() {status = 'open';socket.end();}); socket.setTimeout(1500); socket.on('timeout', function() {status = 'closed';socket.destroy();}); socket.on('error', function(exception) {status = 'closed';}); socket.on('close', function(exception) {callback(null, status,host,port);}); socket.connect(port, host); } function scanCallback(error, status, host, port){ if(status == "open"){ console.log("Reader found: ", host, port, status); } } function singleHost() { checkHost('10.1.1.1', scanCallback); } function multiHost() { var list = ['10.1.1.1','10.1.1.2']; for(var i in list){ checkHost(list[i], scanCallback); } } //Single host - returns ports ok - if others commented out setTimeout(singleHost, 100); // List with two hosts -- they both return nil setTimeout(multiHost, 5000);

Submitted April 23, 2019 at 01:24PM by b7001

First job interview, they want me to pair code. What should I prepare for?

I applied to a position of JavaScript Developer. They said I would be pair coding in NodeJS and jQuery. What I prepare for in advance? Do you think it would be more focused on data structures? Or more like how to build an app?Also I don't memorize the syntax that much, do you think they'd allow me to Google some of the syntax?Thanks!

Submitted April 23, 2019 at 12:37PM by ArizonaIcedOutTea

Node.js lowdb: a lightweight database alternative

https://helpdev.eu/node-js-lowdb-a-lightweight-database-alternative/

Submitted April 23, 2019 at 10:50AM by helpdeveu

Trying to create 'customer accounts' for e-commerce practice site using node, but CustomerID needs to be created every time, any help please?

Not sure if this is the right place to post this, any other suggestions welcome.So I have created a simple e-commerce site for my computing class. The lecturer is currently unable to assist much as he is busy doing interviews. I have also created a MySQL database with three tables to conatain the data for the site. They are:customer orders product I have the following code as a .js file to try to input data to the database://Make sure Express & MySQL modules are installed to this folder var express = require("express"); var app = express(); var path = require("path"); var mysql = require('mysql'); var bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); //Create connection to database var con = mysql.createConnection({ host : 'localhost', user : 'root', password: '****', database: 'frick_and_lonty' //the database you will connect to. }); //Path to html file used for input app.get('/',function(req,res){ res.sendFile(path.join(__dirname+'/input.html')); }); //Commands to add data to table app.post('/submit',function(req,res){ //Add data from form on inputmysql.html to below variables var username=req.body.username; var password=req.body.password; //Send some output to the browser to show the user what was entered... res.write('You sent the name "' + req.body.username + " " + req.body.password + '".\n'); //Create our connection to the database & run the INSERT query con.connect(function(err) { if (err) throw err; //We create out INSERT query using the variables above var sql = "INSERT INTO customer (Email, Password) VALUES ('"+username+"','"+password+"')"; //Execute the query against the database con.query(sql, function (err, result) { if (err) throw err; console.log("1 record inserted"); //Show a confirmation on the terminal res.end(); }); }); }) app.listen(8080); console.log("Running at Port 8080"); ...but this throws the following error, as CustomerID is the primary key for the customer database, and therefore cannot be NULL: Error: ER_NO_DEFAULT_FOR_FIELD: Field 'CustomerID' doesn't have a default value So what do I do? I need some code to create CustomerID as users are created and entered, right?TIA

Submitted April 23, 2019 at 10:00AM by double-happiness

Help on reconnecting modbus comms

https://pastebin.com/a9QduTNiThis is my first node.js Code.How can I make it faster?How can I catch lost modbus connection and try to reconnect?The module i am using is modbus-stream.

Submitted April 23, 2019 at 08:18AM by umbaman

Monday 22 April 2019

Using Clean Architecture for Microservice APIs in Node.js with MongoDB and Express

https://youtu.be/CnailTcJV_U

Submitted April 23, 2019 at 03:52AM by devmastery

Node program can't parse JSON file

https://hastebin.com/eyivopoqer.js - This is the program I'm testing currently.This errors out with: TypeError: Cannot read property 'romfilepath' of undefinedHere is the json file I'm trying to parse:{ "botsettings":{ "token": "tokenhere", "adminroleid": "", "botchannelid": "idhere" }, "emulatorsettings":{ "romfilepath": "./mario.gba", "savefilepath": "./gba.sav" }, "miscsettings":{ "buttonrepeatlimit": 10, "newscrnshtlimit": 10, "scrnshtdelay": 1.5, "helpmsg": "string" } }

Submitted April 22, 2019 at 10:03PM by EuphoricPenguin22

Where to store users' JWT token in order to be reused?

I'm loving Node.Js so far. It's been only a few days since I started, and I ran into an issue of sorts.So I've created a simple register/login API, it's using jsonwebtoken. I hooked up with Mongo and it's working great, although the Authorization header needs to be set on any endpoints that are not supposed to be accessed by guests.I'm moving onto actually making an HTML form that users will be able to use, and my question is where do I store and how do I retrieve the token so I can append it on every request after the user has been logged in? Is there are a better approach to this? What are my options?Thank you!

Submitted April 22, 2019 at 09:17PM by b0zhidar

The Pitfalls of Async/Await in Array Loops

https://medium.com/dailyjs/the-pitfalls-of-async-await-in-array-loops-cf9cf713bfeb

Submitted April 22, 2019 at 07:49PM by efofex55

Opinions on FeathersJS?

I would normally give it a try myself but I find myself spread pretty thin these days so I would be grateful if someone could share some experiences about it before I would jump into it and potentially save me some time.I'm mostly interested in how is it compared to putting together your own stack. From a bit of reading, it wraps express, passport, knex, socketio and some other bits and pieces, this is roughly what I'd pick (except koa vs express) when building something myself. Any war stories in comparison to just grabbing those and putting them together? Did it make things easier or just replaced some issues with different issues?​Really any experience from usage would be great to hear. Thanks!

Submitted April 22, 2019 at 08:01PM by mitom_

Node.js needs to be further optimised (general performance) or it will start to disappear.

Alright I know benchmarks are to be taken with very lightly as they have many caveats etc and we know Node faired extremely well in the last Stack Overflow developer survey: https://insights.stackoverflow.com/survey/2019This isn't news, we all know this: Node.js isn't the fastest framework out there, if we want speed there are other tools we should be looking at.Node is convenience, Node is tools, Node is vastly available resources etc...It ain't no slouch either, BUT (there's always a but) when comparing Node.js to its competition and other frameworks, it falls behind.I'm talking about the infamous computer language benchmarks game: https://benchmarksgame-team.pages.debian.net/benchmarksgame/which-programs-are-fast.htmlhttps://en.wikipedia.org/wiki/The_Computer_Language_Benchmarks_GameAgain, let's not look at these benchmarks like it's the holy bible sent from above written by the messiah himself.Yet, I have no reason not to believe that .NET Core, Go and Java all produce faster software than Node. Everything I've read so far say this holds true (and I will only read later half of 2018 and 2019 material).I also have no reason to believe Node doesn't have any room for improvement.If .NET Core can do it, so can we. .NET pretty much reinvented itself and is now a top contender. There's simply been too much investment in Node to let it fall behind, all the packages and tools we depend on are quite important for myself and my daily life and I know this applies to many of us here too.But servers are also quite expensive, and the world is getting pretty crispy. Anything that can help reduce cost and power is always welcomed, and it looks like more can be done.​Thoughts?

Submitted April 22, 2019 at 07:32PM by SocialMammoth

trying to get into backend using nodejs and feeling lost

Hi, thanks for paying attention to this post. I am trying to learn back end on my own. I've got into front end before, so I learned basic html, css, javascript. Then I decided to pursue a career in back end. I had to choose a language and decided not to waste time learning new syntax and rules and choose node.js since I already had knowledge of javascript and heard that it is quite a good choice. The thing is that lots of people who start learning node.js come from different back end languages and things make sense to them because of their previous experience. I fear that I'm not good enough to start learning this technology. Currently, I'm taking Learn and Understand NodeJS by Anthony Alicea and yeah most of the material is comprehensive, but I have this disbelief that I am not going anywhere with this. Maybe the reason for that is that before getting into nodejs I had never learned asynchronous javascript, es6, callbacks and such other concepts. Overall, the question is how to become a nodejs developer, what's the actual path of learning things on my own so that I'll be able to digest the next material without getting overwhelmed and having fears of not having enough knowledge. And how much javascript will suffice for nodejs, how should I solidify my javascript? I'm thinking of taking Understanding the weird parts by Anthony Alicea course for javascript too. I'm sorry for this poorly formatted post but any feedback, opinion, advice would be greatly appreciated.

Submitted April 22, 2019 at 07:38PM by R2UR

Jest tests (with just 1 suite) taking 21 seconds.

I have 1 test suite in my project, which uses the beforeAll hook to read five images from the file system.Then, the test simply asserts that two objects match.There are three files at play - the test suite, the file containing the function being tested, and a utility functions which permits returning a promise from fs.readFile()Utility Function: ```javscript const fs = require('fs');// Promisify the fs module for read file. module.exports.readFile = (filePath) => { return new Promise((resolve, reject) => { fs.readFile(filePath, (err, data) => { if (err) return reject(err); return resolve(data); }); }); } Function that is being tested: javascript // Append the size category property to all images. transformImageObjectProperties(images) { return images.map(image => ({ ...image, sizeCategory: 'unchanged' })); } Test File: // The general properties available on a received image from the client. const generalImageProperties = { filename: 'product-images', originalname: 'originalname', encoding: '7bit', mimetype: 'image/jpeg', buffer: null, size: 0 };// The array containing all image objects as if we have just received them from the client with multer. const completeTestImageObjects = [];beforeAll(async done => { // The images with which we will be performing tests. const fileNames = [ 'test-image-one.jpg', 'test-image-two.jpg', 'test-image-three.jpg', 'test-image-four.jpg', 'test-image-five.jpg', ];// Get array of pending promises const promises = fileNames.map(async fileName => { return await readFile(`${__dirname}/assets/${fileName}`); }); // Get all buffers from settled promises. const buffers = await Promise.all(promises); buffers.forEach((testImageBuffer, index) => { completeTestImageObjects.push({ ...generalImageProperties, originalname: fileNames[index], buffer: testImageBuffer, size: testImageBuffer.byteLength }); }); done(); });describe('Image Object Properties', () => {// Transform Image Object Properties test('should append the property "sizeCategory" with value "unchanged" to each supplied image', () => { // The transformed objects that came back from the class. const transformedImageObjects = transformImageObjectProperties(completeTestImageObjects); transformedImageObjects.forEach((imageObject, index) => { expect(imageObject).toEqual({ ...completeTestImageObjects[index], sizeCategory: 'unchanged' }); }); }); }); ``` The test itself takes 14 seconds, and the entire test suite takes 21 seconds to complete. I would appreciate any insight as to why this is taking so long. Thank you.

Submitted April 22, 2019 at 07:38PM by JamieCorkhill

How to properly store JWT in localStorage for a cross-functional app?

I have a quick question. I'm using JWT with passport's Google strategy for oauth. I'm signing a token, sending it to the client and then when hitting another route, the token should be passed in as a header, i.e. Authorizaiton: Bearer 1234lk2m41lk32m. I have a helper function that verifies the token:const verifyToken = (req, res, next) => { const token = req.headers['authorization'].split(' ')[1]; if (!token) return res.status(401).send({ auth: false, message: 'No token provided.' }); JWT.verify(token, process.env.JWT_SECRET, (err, decoded) => { if (err) { return res .status(500) .send({ auth: false, message: 'Failed to authenticate token.' }) }; // Set token to localstorage here? res.locals.JWT = token; next(); }); }; Since mobile will be using this app, I'm trying to set it to localStorage, is res.locals = token the right way to do this? Afterwards, I'm thinking of writing a function to get the current user from the id stored in the JWT and then figure out persistent logins.

Submitted April 22, 2019 at 06:22PM by marbles12

Basic question about streams

Let's say I am doing something like:input.pipe(output); input is a readable stream of a file that exists in a temp folder. My question: will there be a problem if that temp folder is deleted before the stream has finished piping?Here is a code example that better illustrates it:/** * I am trying to pipe from a readable stream (which exists in a temp folder), * to a writable stream in my assets folder. Once the stream has finished piping * or if there was an error, I want to delete the temp folder. */ const fs = require('fs'); const path = require('path'); const { deleteFolder } = require('./utils'); try { const tempFolderPath = path.join(__dirname, 'temp'); const inputPath = path.join(tempFolderPath, 'file.txt'); const outputPath = path.join(__dirname, 'assets', 'file.txt'); const input = fs.createReadStream(inputPath); const output = fs.createWriteStream(outputPath); input.pipe(output); } catch (error) { console.error(error); } finally { // I want to delete the temp folder regardless if there was an error or not. // However, I am worried if there could be an issue if this runs before the // `input.pipe(output);` line completes because the `input` stream exists // inside `myFolder`. deleteFolder(tempFolderPath); } This code seems to be working for me, but I wonder if it is just because my file is small and it is able to pipe quickly before the deleteFolder() runs. Any help would be appreciated, thanks!

Submitted April 22, 2019 at 06:58PM by zaynv

Fetch vs. a traditional form?

Is the only reason why we use event listeners and fetch in client-side JS instead of the
so we don’t have to refresh the page?Thank you.

Submitted April 22, 2019 at 06:08PM by b0zhidar

Kyle Simpson: I Don't Hate Arrow Functions

https://davidwalsh.name/i-dont-hate-arrow-functions

Submitted April 22, 2019 at 04:57PM by fagnerbrack

How to solve simple image capcha and submit it using puppeteer?

I have searched on this topic but did not find anything relevant. I think I just need to select the image class/id in that page using puppeteer. And then process that image. But I did not find a good simple-image-capcha solver in js. Most of them are implemented in python.

Submitted April 22, 2019 at 05:13PM by iaminbadland

Documenting a NodeJS REST API with OpenApi 3/Swagger

Hello everyone!I'd like to share with you all this post I've written. You will save time and improve your team communication by documenting your NodeJS REST API with OpenApi 3/Swagger.

Submitted April 22, 2019 at 05:03PM by raparicio6

10 Interesting JavaScript and CSS Libraries for April 2019

https://tutorialzine.com/2019/04/10-interesting-javascript-and-css-libraries-for-april-2019?857

Submitted April 22, 2019 at 04:15PM by Op69dong

Learn Node.js by building real-world applications with Node, Express, MongoDB, Mocha, and more!

https://medium.com/@rodrigmartian/learn-node-js-by-building-real-world-applications-with-node-express-mongodb-mocha-and-more-6538af0bfdbc

Submitted April 22, 2019 at 03:51PM by Alliyasum

I made a youtube-dl script to download all youtube subscriptions (using youtube API)

https://www.reddit.com/r/DataHoarder/comments/bg1g78/i_made_a_youtubedl_script_to_download_all_youtube/

Submitted April 22, 2019 at 02:38PM by SPD_

Stuck on writing an end-to-end test helper. If I write "testcafe firefox ./tests/e2e" directly (in the command line) it works fine, but running that command through exec from child_process doesn't.

Here is my code: https://pastebin.com/RneJ4VGgI'm writing this script so I don't need to write two separate entries in package.json for testing with a simulated instance of Firefox and a simulated instance of Chrome, I just have one which runs ts-node ./tests/e2e/init.ts. As the title says, if I trigger the end-to-end tool (testcafé) directly, it works fine. But if I run this script then the simulated windows appear and the tests are carried out but there is no visual feedback from the tool. How do I retain that visual feedback, is there something else I need to kill in my code besides rl with .close()? Here is a screenshot of the error I receive instead of testcafé's standard feedback.

Submitted April 22, 2019 at 02:55PM by beefyjon

Help: EventEmitter event not received

https://stackoverflow.com/questions/55795147/eventemitter-event-not-received

Submitted April 22, 2019 at 02:30PM by mypirateapp

How to securely build Docker images for Node.js

https://dev.to/lirantal/how-to-securely-build-docker-images-for-node-js-4d7o

Submitted April 22, 2019 at 12:31PM by lirantal

Looking for contributor for Opensource Collaboration ChatApplication

Hey All,I build an app for doing one to one & room chat, here is the github for that application, i open sourced that, now i have a plan to convert that into desktop app & chat server i am continuously working with that & now i think i need more hand to make it working good.​so if you are interested into the open source marketing or open source development, please feel free to connect with me, so we can plan things accordingly.​My plan for making money for this is with enterprise plan or freemium model like wordpress.com, or magento.com.​so please give me some directions if you know some thing about open source marketing too.​link: https://github.com/post2seth/node-chat-one-to-one

Submitted April 22, 2019 at 01:01PM by post2seth

In case you've ever wondered what you can do with fold/reduce I've published: Rewriting functions with fold and reduce

https://maex.me/2019/04/rewriting-functions-with-fold-and-reduce/

Submitted April 22, 2019 at 01:11PM by mstruebing

Sequelize, is it possible to get all of a Model's associated records using the model instance?

If I've setup an association User.hasMany( models.Messages )And when I get a Model instance targetUser from using models.User.findOne({ where:{id: a_user_id} }).then(targetUser) =>Can I just simply call a method like targetUser.getAllMyMessages() I don't want to have to search all the messages where the userId equals ... that seems inefficient (because what if there's over a million messages).

Submitted April 22, 2019 at 06:46AM by horrofan

Sunday 21 April 2019

Enhanced logging for Node.js prod servers to easily correlate logs within 1 async function call

https://danoctavian.com/2019/04/13/thinking-coroutines-nodejs-part2/

Submitted April 22, 2019 at 05:12AM by dandroid3000

Looking for a contributor to the Hyron project

#find_contributorHi everyone, I am developing a solution that allows maximum reuse of source code and saves time in server-side application development. That's Hyron: https://docs.hyron.orgThis is an open source project, and we are in the midst of pregnancy. We look forward to receiving contributions from everyone, so that it can make it more perfect and powerfulI hope that in the future, we can develop a project more quickly and simply, not only stop at NodeJS, make the most of the power of the community, even drag and drop. to create a powerful applicationhttps://i.redd.it/t59fufwbuqt21.jpg

Submitted April 22, 2019 at 05:33AM by thangdjw

Sequelize, how to do I create a new Record with two foreign keys?

I need to save a message with two user ids (sender and receiver). So I have a Message model and a User model. With the associations, User hasMany Messages and Message belongs to User & Message belongs to UserSo in the router or controller or whatever, I want to be able to...chat.router models.Message.create({ message: req.body.message; senderUserId: req.body.senderId, recieverUserId: req.body.recieverId, }).then( () => { ... blah ... }); or it might be better to do something like models.Message.create({ message: req.body.message; include[ models.User.findUserById(senderid) as 'sender' , models.User.findUserById(senderid) as 'receiver' , ]; }) Im not sure that I'm using the foreign key correctly, (I've never had to use one so far).So my User.Model schema looks like this, 'use strict'; module.exports = (sequelize, DataTypes) => { const User = sequelize.define('User', { email: DataTypes.STRING, password: DataTypes.STRING, firstName: DataTypes.STRING, lastName: DataTypes.STRING, }, { createdAt: false, updatedAt: false }); .... User.hasMany(models.Message); }; return User; }; and my Message.Model schema looks like this, 'use strict'; module.exports = (sequelize, DataTypes) => { const Message = sequelize.define('Message', { message: DataTypes.STRING }, { createdAt: 'dateSent', updatedAt: false }); Message.associate = (models) => { Message.belongsTo(models.User,{ foreignKey:{ name:'senderUserId', allowNull: false, } }); Message.belongsTo(models.User,{ foreignKey:{ name:'recieverUserId', allowNull: false, } }); }; return Message; };

Submitted April 22, 2019 at 04:37AM by horrofan

Black-box Testing a Node.js Web API

https://medium.com/@grantcarthew/black-box-testing-a-node-js-web-api-d626f7d651be?sk=752454287184e662f3792a281a50527b

Submitted April 22, 2019 at 03:52AM by r-wabbit

Node Unit Testing Image Resizing with Jest

I have a function which, dependent upon a series of arguments, resizes images in particular ways and to particular dimensions.What would be the best way to test that method with Jest, considering it requires a valid image file?Thank you.

Submitted April 22, 2019 at 01:58AM by JamieCorkhill

TypeError: generateKeyPair is not a function when trying to use a function in the node.js crypto module

I'm trying to use the node.js module crypto to generate key pairs, but for some reason I cannot seem to use the generateKeyPair function.I made sure crypto was installed and up to date, but nothing changed. Both the official docs and multiple SO answers show exactly the code I used, but don't work.The code I used is this:const { generateKeyPair } = require('crypto');generateKeyPair('rsa', {modulusLength: 4096,publicKeyEncoding: {type: 'spki',format: 'pem'},privateKeyEncoding: {type: 'pkcs8',format: 'pem',cipher: 'aes-256-cbc',passphrase: 'top secret'}}, (err, publicKey, privateKey) => {});

Submitted April 22, 2019 at 12:23AM by codegreen_

What are the most important things a full stack dev should know about backend development in Node.js?

I work as a full stack freelance developer. My focus is React/React Native frontend, Node.js backend. Usually with MongoDB and GraphQL. I have a few years of experience and I want to improve on the backend, but not sure what the next steps for me are.I know there's a tonne of stuff I could still learn about the frontend, but backend seems somewhat simple. Build an API. Communicate with the DB. Set up auth. Handle the business logic. Some devops. Testing. Be familiar with different packages at your disposal.How do you level up as a backend dev? The people that only focus on backend and work in it full time, where is the heavy work? What turns one from average backend dev to expert?

Submitted April 21, 2019 at 10:52PM by elie2222

Writing tests for controllers with Jest?

I'm building an app and using sequelize for my DB. I'm unsure what approach I should take to writing tests for my controllers using sequelize. Am I supposed to seed the database and then test the controllers using the seeded database? I have a few associations that might be a pain to seed but I don't know if there's a better approach. I've been googling a lot but I can't seem to find anything specific to sequelize testing with jest.Any advice would be appreciated!

Submitted April 21, 2019 at 10:23PM by RubyNewbie-

IMDb API Vue Component to render a Watchlist

https://github.com/kunalnagar/vue-imdb

Submitted April 21, 2019 at 10:24PM by kunalnagar

Where should I store the admin password

Hello,I am working on backend system and need to implement an admin dashboard with login.In the future, I intend on adding support for multiple admin users with different roles. This will be stored on a 'Admins' db.For now, I just need to add a single admin user for the MVP.I have a .env file that contains the JWT secret, database passwords etc.Is it okay to store the database password there? Any reason to hash it?

Submitted April 21, 2019 at 08:08PM by JerryNotAgain

Simple descriptive code snippets for basic node.js concepts

Node-gems -- I have created a Node.js project with descriptive snippets of code to cover the fundamentals of Node.js. Check it out here : https://github.com/fardeen9983/Node-gems

Submitted April 21, 2019 at 05:34PM by fardeen9983

PHP dev using Node for the first time; stuck on world's simplest use case. I need to return a value from a DB and store it to a variable.

As the title suggest, I'm embarrassingly stuck on what I thought would be the simplest thing I had to do all day.Say I have a function called getCountOfGreenShirts. I want to hit the database, perform a simple COUNT, and store the number returned to a variable.Pseudocode:private getCountOfGreenShirts():number { var connection = await mysql.createConnection({ ... }); var count = 0; connection.query('SELECT count(*) as count FROM `shirts` WHERE `color` = "Green"', function (error, results, fields) { if (error) throw error; console.log(results[0].count); //Returns correct value count = results[0].count; }); console.log(count); //Returns 0 return count; } The class I am working on has a computed property, to be dynamically determined every time it is instantiated. The logic that drives this computed property is dependent on several values pulled from the database, such as the example above.I'm aware that my attempted approach won't work due to Node being asynchronous. I spent the day trudging through Stack Overflow and Medium, but for the life of me I can't find an example/best practice as to how to handle this simple use case. I switched from the mysql npm package to mysql2 to incorporate async/await/promise handling, but after several hours of trial and error got absolutely nowhere.If anyone can point me in the right direction, I'd really appreciate it. If you can show me a tutorial I'll gladly follow it, a video I'll gladly watch it, or any source code I'll gladly read through it. At this point, if anyone can just show me how the hell to correctly pull a value from a mysql database, I'll happily buy them Gold.

Submitted April 21, 2019 at 05:19PM by _SevenDeuce

Instagram meme bot using puppeteer

Hello,I have made a instagram bot that post memes from r/dankmemes. The bot post one meme every hour, and to be able to post I use puppeteers emulate function to emulate an iphone. The bots name is @god.memz. If you have any questions I would be happy to answer them below.

Submitted April 21, 2019 at 03:33PM by hemligatjansten

From 'PHP' -> 'Node.js event/loop' ... dealing with multiple web requests + database connections + privacy concerns?

I'm coming from a PHP background where things are pretty simple...Everything is synchronousEvery web request is in an entirely 'new + separate + private' PHP process that is killed as soon as the response is sentI never had a need to make multiple connections to a database from within a single PHP processNow I'm moving over to Node.js, and things are obviously quite different here given the event/loop model...where multiple web requests can be served by a single Node processlots of async things might be going on within a single process waiting for stuff to finishyour Node process could be holding some sensitive data in memory that only the relevant user should be able to accesssome of the users of your website might be doing stuff that involves slower database queries than others...so I'm wondering does this mean that each web request received by Node should create its own database connection, so that the slow requests don't block the fast ones?Obviously might not matter on small sites with only fast queries, so lets assume we're talking about bigger sites with parallel fast + slow queries to consider.I'm using postgres, but would be interested to hear if there are any differences with other databases.Also keen to hear any tips in general that might be good to know for people new to event/loop web servers coming from PHP backgrounds etc. I haven't even started to think about how security works here... seems like an area where you could easily make some mistakes when you're used to each application process being entirely private. Any guides or anything out there with some tips?

Submitted April 21, 2019 at 03:22PM by r0ck0

Node + Pug. How to Filter data without reloading page

I suppose the best example of what I want is nomadlist.com If you click the filters:1) the url changes (think using pushState)2) the filtered data comes back from backend3) But the whole page doesn't refresh. Spinner spins. Data reloads.I've got it to a stage where if on click on the filters, you get a different response back from the backend. But I've got to loop through this response and append to a div (or reload just part of the page)I think I could use .innerHTML , but just doesn't feel right. I'd rather pass the data into a mixin somehow (but not quite sure how that's possible).Advice welcome. Thanks a lot for any help. Not keen on using JQuery.

Submitted April 21, 2019 at 01:25PM by harrydry

Choosing the right Node.js Framework: Next, Nuxt, Nest

https://nodesource.com/blog/next-nuxt-nest

Submitted April 21, 2019 at 09:31AM by harlampi