Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Osmosisch
Sep 9, 2007

I shall make everyone look like me! Then when they trick each other, they will say "oh that Coyote, he is the smartest one, he can even trick the great Coyote."



Grimey Drawer
I think it's also worth nothing that because your client variable isn't explicitly declared as a var, it is actually a global and won't be GC'ed at all.

Adbot
ADBOT LOVES YOU

HappyHippo
Nov 19, 2003
Do you have an Air Miles Card?

fankey posted:

I understand that in
code:
client.on('data', (chunk) => { ws.send(data); });
closures are used so that ws is not destroyed as long as that function is attached to the socket event handler. In my code I think i have
  • ws event handlers which use closures containing the socket
  • socket event handlers which use closures containing the ws
so it makes sense that the socket will not be removed until the ws is and the ws won't be removed until the socket is. What's not clear to me what is making the ws still reachable after the add() method is returned. The WebSocketServer has an option to retain a list of clients but if I don't do that I don't think there is anything that tethers the ws to the global scope.

Well who's calling add? They pass in the value of ws. If they hold onto it afterwards then clearly ws is reachable and by extension so is client. Ultimately a javascript program must have some "root" from which to consider objects reachable. In the browser this is document and callbacks attached to DOM elements. Not sure how it works in Node. A circular reference won't leak - it will be cleaned up if it isn't reachable.

BTW, did you intend for client to be a local variable? As written, client is actually a global variable, since you never used var when declaring it. Use strict mode to catch this kind of error.

HappyHippo
Nov 19, 2003
Do you have an Air Miles Card?
Also, if you (or anyone else) want the nitty gritty of how closures, prototypes and garbage collection works, read this: http://jibbering.com/faq/notes/closures/ It's kinda old so it talks about an ancient internet explorer bug but it's otherwise a very good reference IMO.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Osmosisch posted:

I think it's also worth nothing that because your client variable isn't explicitly declared as a var, it is actually a global and won't be GC'ed at all.

Oh son of a bitch! I used to trigger on that kind of thing really hard - must be getting soft :\

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

fankey posted:

Pretty simple - every time a new web socket comes in ( via require('ws').Server ) I create a TCP socket and set up handlers on both the socket and ws to shovel data between them. If an error occurs on either one I close down the other side. It all pretty much works but I'm not clear what I need to do with regards to clearing stuff out so the gc can delete the objects.

In my code I'm not storing any references to either the ws or socket - they appear to go out of scope when add() returns. At this point are they eligible for gc and could be yanked out from under me? If so, should I just store them in a collection manually? If they somehow aren't eligible for gc then I have the opposite quesiton - what do I need to do once I'm done with both connections to ensure the gc will clean up memory for me? Or do things just magically work and I don't need to worry about such things - which is hard for someone with years of C++ and C# development to come to terms with.

Everyone's first production Node project leaks memory like a sieve. JavaScript wasn't designed with long running processes in mind. It was supposed to run on a webpage that gets cleared out as soon as you click on anything. JavaScript doesn't gc oftentimes seemingly regardless of whether the object can logically be ever used. It therefore requires a great deal of care to write for Node.

In depth closures understanding will be necessary and at some point you'll have to begin explicitly setting variables to `undefined`.

Nolgthorn fucked around with this message at 02:46 on Jan 29, 2017

Loving Africa Chaps
Dec 3, 2007


We had not left it yet, but when I would wake in the night, I would lie, listening, homesick for it already.

code:
var textLayer = drugchart.internal.main.select('.' + c3.chart.internal.fn.CLASS.chartTexts);
                  textLayer.remove();
                  for(var i=0;i<5;i++)
                  drugchart.internal.mainCircle[i].forEach(function (point, index) {
                      var d3point = d3.select(point);
                      textLayer
                          .append('text')
                          // center horizontally and vertically
                          .style('text-anchor', 'middle').attr('dy', '.2em')
                          .text($scope.labels[i])
                          // same as at the point
                          .attr('x', d3point.attr('cx')).attr('y', d3point.attr('cy'));
                  })
I'm writing a project and using c3.js. One of the things i need to do is add in some custom labels. The above code adds labels correctly but as the data points move it the label stays where it is and an additional one added to its new position. all the examples i've seen suggest the above code should work when it's called but it only removes the labels and doesn't replace them. What am i doing wrong?

Loving Africa Chaps
Dec 3, 2007


We had not left it yet, but when I would wake in the night, I would lie, listening, homesick for it already.

Loving Africa Chaps posted:

code:
var textLayer = drugchart.internal.main.select('.' + c3.chart.internal.fn.CLASS.chartTexts);
                  textLayer.remove();
                  for(var i=0;i<5;i++)
                  drugchart.internal.mainCircle[i].forEach(function (point, index) {
                      var d3point = d3.select(point);
                      textLayer
                          .append('text')
                          // center horizontally and vertically
                          .style('text-anchor', 'middle').attr('dy', '.2em')
                          .text($scope.labels[i])
                          // same as at the point
                          .attr('x', d3point.attr('cx')).attr('y', d3point.attr('cy'));
                  })
I'm writing a project and using c3.js. One of the things i need to do is add in some custom labels. The above code adds labels correctly but as the data points move it the label stays where it is and an additional one added to its new position. all the examples i've seen suggest the above code should work when it's called but it only removes the labels and doesn't replace them. What am i doing wrong?

i needed to do

code:
  textLayer.select('text').remove();
or better still

code:
_.each(drugchart.internal.mainCircle, function(){
                    textLayer.select('text').remove();
                  })
underscore ftw

Loving Africa Chaps fucked around with this message at 14:49 on Jan 29, 2017

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

fankey posted:

In my code I'm not storing any references to either the ws or socket - they appear to go out of scope when add() returns. At this point are they eligible for gc and could be yanked out from under me? If so, should I just store them in a collection manually? If they somehow aren't eligible for gc then I have the opposite quesiton - what do I need to do once I'm done with both connections to ensure the gc will clean up memory for me? Or do things just magically work and I don't need to worry about such things - which is hard for someone with years of C++ and C# development to come to terms with.

The javascript GC actually garbage collecting something that you don't want it to garbage collect is polar opposite of the problem I usually have with it (it not loving garbage collecting something that ought to be garbage collected).

Note that there are like, tools for figuring this poo poo out - like, if you follow along with this guide using node inspector https://www.toptal.com/nodejs/debugging-memory-leaks-node-js-applications and using the heap snapshot tool in Chrome, you should be able to test whether or not you actually have a problem.

Cugel the Clever
Apr 5, 2009
I LOVE AMERICA AND CAPITALISM DESPITE BEING POOR AS FUCK. I WILL NEVER RETIRE BUT HERE'S ANOTHER 200$ FOR UKRAINE, SLAVA
Junior front-end dev here. I had two coworkers voice preference for relying on for loops over the higher order array methods like forEach, map, filter, and reduce. Ignoring browser compatibility entirely, where would people here come down on this? My own thinking is that there's no clarity lost in the higher order functions, and they more succinctly achieve their intended task. I'm self-taught, so had picked up the methods in Eloquent Javascript, which suggests them to have no substantial efficiency costs. No dog in this fight, just looking to broaden my understanding of the language.

Roadie
Jun 30, 2013

Cugel the Clever posted:

Junior front-end dev here. I had two coworkers voice preference for relying on for loops over the higher order array methods like forEach, map, filter, and reduce. Ignoring browser compatibility entirely, where would people here come down on this? My own thinking is that there's no clarity lost in the higher order functions, and they more succinctly achieve their intended task. I'm self-taught, so had picked up the methods in Eloquent Javascript, which suggests them to have no substantial efficiency costs. No dog in this fight, just looking to broaden my understanding of the language.

Uses of map/filter/reduce are (if you use them right) almost all easier to re-understand in the future than a loop, and there's a performance difference but it's not one that actually matters unless you're processing huge amounts of data all the time.

forEach is pointless once you've got for-of syntax working, though, since forEach only got used in the first place because for-in syntax is broken for most uses.

ROFLburger
Jan 12, 2006

I normally prefer array methods unless I'm doing something special like exiting early. They're easier to read and you don't get as much of an opportunity to make boneheaded mistakes with indexes and incrementation.



Also they're more *~~ declarative ~~*

Chenghiz
Feb 14, 2007

WHITE WHALE
HOLY GRAIL

ROFLburger posted:

I normally prefer array methods unless I'm doing something special like exiting early. They're easier to read and you don't get as much of an opportunity to make boneheaded mistakes with indexes and incrementation.



Also they're more *~~ declarative ~~*

This, but also you can exit early by using Array#some() if you need to!

Sab669
Sep 24, 2009

(Posting from my phone at work, sorry for poor formatting.)

TL:DRI'm looking for a JavaScript library to help iterate over HTML elements. Any suggestions?

I had to do something very similar to this in C# last week. I used HTML Agility Pack for this and it was fairly easy to use once I got the hang of it. For that project, I was iterating over a table and pulling out the InnerText; fairly simple. This time around it's a bit more complicated.


I've got a table within a div, within a table, within yet another table. So we're 3 tables deep. Thankfully (surprisingly) the div containing the table I care about has an ID so it's easy to find.

This final table has N rows and 4 columns. The number of rows is generated dynamically at run time to include a number of input controls to act as search parameters for the user.

I'm trying to basically combine the plain text in the "odd numbered" <TD> elements, then get the value of the control within the "even numbered" <TD> elements.

Now that I've typed it out it doesn't sound too hard but I can't figure out how to do it with just plain JS. I tried using document.GetElementById("myDivID"), then use getElementsByTagName to get the table, but this doesn't give me its child nodes (unsurprisingly). I tried passing "input" to that as well, but I'm getting far more controls in that collection than I can see on the page, which might be due to the third-party controls we use.

geeves
Sep 16, 2004

Sab669 posted:

(Posting from my phone at work, sorry for poor formatting.)

TL:DRI'm looking for a JavaScript library to help iterate over HTML elements. Any suggestions?

I had to do something very similar to this in C# last week. I used HTML Agility Pack for this and it was fairly easy to use once I got the hang of it. For that project, I was iterating over a table and pulling out the InnerText; fairly simple. This time around it's a bit more complicated.


I've got a table within a div, within a table, within yet another table. So we're 3 tables deep. Thankfully (surprisingly) the div containing the table I care about has an ID so it's easy to find.

This final table has N rows and 4 columns. The number of rows is generated dynamically at run time to include a number of input controls to act as search parameters for the user.

I'm trying to basically combine the plain text in the "odd numbered" <TD> elements, then get the value of the control within the "even numbered" <TD> elements.

Now that I've typed it out it doesn't sound too hard but I can't figure out how to do it with just plain JS. I tried using document.GetElementById("myDivID"), then use getElementsByTagName to get the table, but this doesn't give me its child nodes (unsurprisingly). I tried passing "input" to that as well, but I'm getting far more controls in that collection than I can see on the page, which might be due to the third-party controls we use.

JavaScript is a little weird with tables and childNodes. Technically each table has a <tbody> and <thead> I believe, even if you do not declare them. Best to go after them explicitly: (Edit: also there are technically 9 childNodes of <tr> in this example, not 4)

https://jsfiddle.net/createanaccount/z56yesz0/

geeves fucked around with this message at 14:47 on Feb 7, 2017

There Will Be Penalty
May 18, 2002

Makes a great pet!

Sab669 posted:

(Posting from my phone at work, sorry for poor formatting.)

TL:DRI'm looking for a JavaScript library to help iterate over HTML elements. Any suggestions?

I had to do something very similar to this in C# last week. I used HTML Agility Pack for this and it was fairly easy to use once I got the hang of it. For that project, I was iterating over a table and pulling out the InnerText; fairly simple. This time around it's a bit more complicated.


I've got a table within a div, within a table, within yet another table. So we're 3 tables deep. Thankfully (surprisingly) the div containing the table I care about has an ID so it's easy to find.

This final table has N rows and 4 columns. The number of rows is generated dynamically at run time to include a number of input controls to act as search parameters for the user.

I'm trying to basically combine the plain text in the "odd numbered" <TD> elements, then get the value of the control within the "even numbered" <TD> elements.

Now that I've typed it out it doesn't sound too hard but I can't figure out how to do it with just plain JS. I tried using document.GetElementById("myDivID"), then use getElementsByTagName to get the table, but this doesn't give me its child nodes (unsurprisingly). I tried passing "input" to that as well, but I'm getting far more controls in that collection than I can see on the page, which might be due to the third-party controls we use.

Use table_element.querySelector("> tbody > tr > td:nth-child(even)")

(I think that would be the correct selector, I know it would work with jQuery.)

necrotic
Aug 2, 2005
I owe my brother big time for this!
Should work, those are all valid CSS selectors and not one of those neat custom Sizzle selectors.

geeves
Sep 16, 2004

There Will Be Penalty posted:

Use table_element.querySelector("> tbody > tr > td:nth-child(even)")

(I think that would be the correct selector, I know it would work with jQuery.)

This is much better. I keep forgetting that querySelector exists half the time.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



I was going to try to put together an XPath query. I may need professional psychological help.

necrotic
Aug 2, 2005
I owe my brother big time for this!
1-888-NO-XPATH we're here to help

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
document.querySelectorAll is my favorite function

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Ok, I'm wanting to do in Node what I do in Django. What's the most popular or best things for doing the main parts of Django in Node? That'd be templating, ORM, user management, form handling...the usual stuff you'd expect out of a batteries-included framework.

I'm not really expecting there to be one framework and that I'll have to glue together stuff, but maybe I'm wrong on that.

Impotence
Nov 8, 2010
Lipstick Apathy

Munkeymon posted:

I was going to try to put together an XPath query. I may need professional psychological help.

If we're going xpath I'd just have clicked inspect element and then right clicked it and Copy > Xpath to get rid of 90% of the work

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Biowarfare posted:

If we're going xpath I'd just have clicked inspect element and then right clicked it and Copy > Xpath to get rid of 90% of the work

The the alternation/nth-child was going to be the 'challenge' because I don't know how to do that off the top of my head.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

Thermopyle posted:

Ok, I'm wanting to do in Node what I do in Django. What's the most popular or best things for doing the main parts of Django in Node? That'd be templating, ORM, user management, form handling...the usual stuff you'd expect out of a batteries-included framework.

I'm not really expecting there to be one framework and that I'll have to glue together stuff, but maybe I'm wrong on that.

Nothing has an out of the box experience comparable to Django in node. My small to medium client projects use Django with node as a templating layer only (limited socket json to HTML back and forth).

You'll be assembling various libraries, some are poo poo, some are not. I've heard reasonable things about knex for databases. React can be your templating (I know you've done plenty of that). i18next for localisation. Express + passport for session auth, but you'll have to build the user table & semantics yourself.

There's probably a form layer that'll plug into express but I've never used it.

I doubt you'll get the auto admin anywhere.

necrotic
Aug 2, 2005
I owe my brother big time for this!
Yeah I think the best approach is to use something else for the backend and the node only for building the frontend if you need it.

Roadie
Jun 30, 2013

Thermopyle posted:

Ok, I'm wanting to do in Node what I do in Django. What's the most popular or best things for doing the main parts of Django in Node? That'd be templating, ORM, user management, form handling...the usual stuff you'd expect out of a batteries-included framework.

I'm not really expecting there to be one framework and that I'll have to glue together stuff, but maybe I'm wrong on that.

The closest you'll probably see is Ember.js, and even that's meant to be more like a Ruby on Rails thing where it maps frontend routes to backend stuff and you hook up your own choice of ORM, etc.

Strapi bundles an ORM and user management and other such stuff, but they're in "next version is almost ready" limbo at the moment.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Thanks for the replies. Why the gently caress is node so popular on the backend if there aren't any good full-feature frameworks for it yet?

(and by popular I mean lots of results on job sites)

Roadie
Jun 30, 2013

Thermopyle posted:

Thanks for the replies. Why the gently caress is node so popular on the backend if there aren't any good full-feature frameworks for it yet?

(and by popular I mean lots of results on job sites)

With Express & company it's extremely easy to get up and running for APIs and for the equivalent of Flask/Sinatra style "start small and keep adding features as you expand" sites.

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

Thermopyle posted:

Thanks for the replies. Why the gently caress is node so popular on the backend if there aren't any good full-feature frameworks for it yet?

(and by popular I mean lots of results on job sites)

It's actually a total mystery what the core value of node.js is - like all the alleged benefits it lists on its website are either completely transparent lies (scalability/concurrency yet still has to be put behind nginix in production !) or prima facie idiotic (run javascript on both the server and the client, so you can just take your front end js wizards and make them back end devs with no training!).

but I think a lot of web devs who are sick of Ruby on Rails are switching to it, and Microsoft is encouraging its use for whatever reason.

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

Bruegels Fuckbooks posted:

It's actually a total mystery what the core value of node.js is - like all the alleged benefits it lists on its website are either completely transparent lies (scalability/concurrency yet still has to be put behind nginix in production !) or prima facie idiotic (run javascript on both the server and the client, so you can just take your front end js wizards and make them back end devs with no training!).

but I think a lot of web devs who are sick of Ruby on Rails are switching to it, and Microsoft is encouraging its use for whatever reason.

It's newer and uses JS, which is better than Ruby & PHP, so it's winning handily in the "too cheap to pay for things" market. Also, recently it has a lot better Windows support than Ruby & PHP. And there is SOME merit to to the code reuse angle, but it often gets overblown (sharing a Data layer library for HTTP calls between a server and UI, for example).

ROFLburger
Jan 12, 2006

Bruegels Fuckbooks posted:

still has to be put behind nginix in production !

Just curious, why is this?

Roadie
Jun 30, 2013

ROFLburger posted:

Just curious, why is this?

There was no real threading available for a long time, and even now you can only do it with libraries that work around it by including C code that gets compiled with node-gyp. This also means that the server frameworks like Express pretty much haven't touched the idea because they're trying to be platform-independent and there's nothing equivalent included in core Node.

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

ROFLburger posted:

Just curious, why is this?

I'm just going to post this without comment:
https://thefullsnack.com/don-t-serve-static-files-with-nodejs-31666462f79c#.ynw7kcwer

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
To be fair, nginx et al probably should still front whatever you do as it provides far more flexibility to actually express the server configuration properly, regardless of the underlying tech choices, but that article still shows the reality of the lie that Javascript is great at concurrent code. It ain't. It's kind of a mockery of it, callbacks doesn't hold a candle to languages with actual understanding of concurrency such as Erlang and the like.

necrotic
Aug 2, 2005
I owe my brother big time for this!
Yeah. It also makes scaling horizontally much simpler.

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.



Now this is just a theory so take it with a grain of salt since I was only in my first or second year of university while this was happening, but:

Node.js came out in 2009, 8 years ago now. Flash back to 2009 and what are a lot of people using for websites (also to set the scene this is before SPAs hit it big)? Things like Python, Ruby, PHP, some lovely C# framework (since this was 2009 and most likely be a legacy product), whatever other thing was out there, etc.

What do a lot of those have in common? Well for one they were all old (except RoR which was very hip at the time), and none of them had great concurrency out of the box[1]. Now some of them like Python did have ways of doing concurrency, but it's all weird third party solutions and they have lots of catches.

Then comes along Node.js, right on time with the start of a new era in Javascript. ES5 was either just coming out or was coming out soon. Single page applications were becoming a big thing. Ajax was a big buzzword. Front-end frameworks were becoming interesting and catching eyes.

Node.js swoops in with these cool promises of "out with boring static types that you don't need, just do TDD" and "we have great concurrency, webpages load so fast because everything is async" and "look at how easy it is to get started and up and running".

It came in at the right time where its benefits compared to other popular solutions at the time were quite nice. Now it was still lovely compared to other solutions (I mean Erlang preceded it by decades still), but in terms of visibility it was much more apparent. It came in at the right time, rode a bunch of trends, and entrenched itself as a competitor. It doesn't necessarily have to have been good, it just had to look good and be there at the right time.

[1] I listed C#, which obviously has threading and all that, and I know Python did too, but I'm talking out of the box in whatever framework you would be using at the time

piratepilates fucked around with this message at 00:11 on Feb 11, 2017

ROFLburger
Jan 12, 2006


lol

Ranzear
Jul 25, 2013

"It's too slow, so let nginx do it... but only half the stuff."

Dafuq...

porksmash
Sep 30, 2008

Ranzear posted:

"It's too slow, so let nginx do it... but only half the stuff."

Dafuq...

nginx can't interpret javascript, and Node isn't efficient serving static files. nginx is extremely good at serving static files, and Node is good at interpreting javascript. None of which matters until you're getting into 100s of requests per second or want to beat some load time benchmark.

Adbot
ADBOT LOVES YOU

Ranzear
Jul 25, 2013

porksmash posted:

nginx can't interpret javascript, and Node isn't efficient serving static files. nginx is extremely good at serving static files, and Node is good at interpreting javascript. None of which matters until you're getting into 100s of requests per second or want to beat some load time benchmark.

This part:

quote:

We have a single process that serving both website contents (HTML, JSON data…) and static files (CSS, JavaScript, Images,…).

Sounds an awful lot like 'static' and 'more static'. If the former is touching dbms or whatever, why not PHP or something.

I mean, I am quite the hardcore JavaScript Heretic, but this sure sounds like using Node just to spite everything else. Maybe it's just lovely examples given and they really mean a proper backend application.

But it also sounds like they only know how to put node behind nginx or not put node behind nginx, instead of putting haproxy in front of both in parallel (and you can terminate your TLS there for both, no less).

Its just a really lovely half-solution even if you had the load to matter.

Maybe that's the joke though.

Ranzear fucked around with this message at 21:44 on Feb 12, 2017

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply