Tag: javascript

I’m a web developer and I’ve been stuck with the simplest app for the last 10 days — Medium

Люто плюсую I’m a web developer and I’ve been stuck with the simplest app for the last 10 days — Medium



(As a side note of irritation, it seems that no matter what you choose, you need some watch tasks running in the background compiling, linting, packing, testing. I write something in my editor, Cmd+S to save, Cmd+Tab to switch to the browser, Cmd+R to refresh the page and I don’t see any difference. Guess what, sometimes I’m faster that the compiler or the “watch” task didn’t notice my editing or it threw an exception.)


Як я його розумію. Ненавиджу розробку сайтиків.

  • Current Mood: thrilled

(no subject)

The Website Obesity Crisis


Let me start by saying that beautiful websites come in all sizes and page weights. I love big websites packed with images. I love high-resolution video. I love sprawling Javascript experiments or well-designed web apps.

This talk isn't about any of those. It's about mostly-text sites that, for unfathomable reasons, are growing bigger with every passing year.

While I'll be using examples to keep the talk from getting too abstract, I’m not here to shame anyone, except some companies (Medium) that should know better and are intentionally breaking the web.

Typical web programmer

Originally posted by tonsky at post
Наверняка, многим серьезным веб-программистом преходилось испытать неприязнь, когда они узнавали, что чтобы выложить веб-сайт надо еще изучать пхп. Все соглашаются (и в интернете я тоже читал) что это очень, очень плохой язык. Это на самом деле глупость и когда я прочитал я долго не мог поверить ходил спрашивал и оказалось не зря. Тепер ьвеб-сайты можно писать на самом популярном в мире языке джаваскрипте. Это революционный переворот и он происходит прямо на наших глазах. Что это значит для нас, ребята? Что мы уже знаем, как писать сйты по сути. Я был шокирован, как там все организовано, но похоже они все вопросы продумали с самого начала и договорились что это будет очень востребованный проект.Более того, умные C++ перцы из гугл которые по утрам ездят в автобусах набитых баскетбольными мечами уже работают над тем, чтобы джаваскрипт работал быстрее С++, потому что он комплируется сразу в результат, минуя стадию вычисления! Вы наверняка заметили это по тому, что gmail.com открывается за 5 секунд, а не 20 как это было в до-интернетную эпоху, может хотя бы самые древние. Его кстати тоже делали в гугл. Что это если не порыв я не знаю. То есть, если вы напишете свой сайт на nodejs, он автоматически будет бытсрым и будет масштабироватсья (обрабатывать столько клиентов, сколько пришло, это настоящая проблема в пхп была и некто не знал как с ней быть). Например, данные между разными запросами не изолированны и вообще можно использовать одни и те же глобальные переменные для всех клиентов и экономить память. В том же пхп это в принципе не возмонжно и засчет этого у ноды такая гиганская производительность. Там даже продумано если вы будете работать с другом или кто-то допустим, то я зык специально за счет очень удобной типизации можно писать так что вы не будете знать что и как вам передает ваш друг. Это очень удобно потому что позволяет меняь програму в одном месте и вообще не парится о том же друге что там у него програма все равно запустится.Только представьте! Любой кусок кода можно насать один раз. Например, функцию, переворачивающущю строку, и вызывать ее из браузера или включать музыку с телефона. Особенно если заморочиться совместимостью северного кода и особеностей разных браузеров. Также они добавили возможность создавать внутри функции другие функции и это очень круто, но я пока не понял как потом вернуться в первую функцию. Но самое главное, что над нодой сейчас работает туча народу просто, они переписывают все что было до них написано на ноду и у них получается лучше потому что они сразу заточились на производительность и чтобы было лучше а так же просто использовать. Например нужно сходить в базу данных создал проект на гитхабе сразу набежали форкнули завтра только пуллреквесты принять и можно заливать в продакшн на свой ноутбук. Сообщество очень дружелюбное, если кому-то удается сделать что-то работающее на ноде его обязательно хвалят и подбадревают потому что это правда успех. Я пока не понял как допустим считать файл но говорят эт из-за безопасности,там все очень надежно, ведь если к тебе вдруг идет миллион клиентов и вы облажаетесь в 10% случаев ты облажаешься перед 100 000 человек. Поэтому например если где-то произошла ошибка лучше сразу аккуратненько завершиться чем пазориться перед остальными, тем более если перезапустить сервер то там и память лишняя освободится и бегать начнет пошустрее, да и перезапускается он очнь бытсро. Иногда бывает быстрее перезапустить сервер чем дождаться окончания сборки мусора. Ктому же nodejs так оптимизирован что никогда не займет больше одного ядра а это значит что базу данных например можно поставить на тот же ноут на другое ядро для экономии ресурсов и надежности (иметь что-то на той же машине всегда надежнее, много ли что, все у кого есть дома интернет вы это итак знаете) и все будет быстро бегать и даже можно во что-нибудь пошпилить или дальше форум по nodejs почитать но тогда надо побольше ядер купить. Но в серверы как раз много ядер и ставят и как видите nodejs прекрасно справляется с этой задачей. Правда что бы писать на ноде нужно купить макбук потому что все примеры в интернете написаны на мак буке но я думаю если выделаете высокопроизводительный веб-сервис, вам всеравно прийдется пройти раунд финансирования у родителей чтобы потом его запускать. Вообщем я в восторге хотя немного напрягает что гдето должны быть проблемы но я пока не понял не столкнулся ая уже очнь долго с ней разбираюсь и пока не понял.

(no subject)

http://www.opennet.ru/opennews/art.shtml?num=46117
Какого "веба"? Развитие гипертекстовой сети остановилось в нулевых.

То что сейчас уеб-макаки понимают под "вебом" это гигантская свалка проприетарного го'нокода и кривых, неудобных интерфейсов к проприетарным базам данных. выкинули, а те, кто когда-то лепил его на каждую страницу, остались и делают то же самое, только теперь средствами джаваскрипта. Ещё и заботливо скрывают остальное содержимое страницы (а то и подгружают на лету), лишь бы пользователь не пропустил получившийся шедевр.
Tags: ,

The emperor’s new clothes were built with Node.js

The emperor’s new clothes were built with Node.js | Notes (beta)



No wonder people love Node.js. It gives you the same performance as lightweight threads but with the clarity and usability of x86 assembly.
Quoth Hacker News: “I switched from a dump truck to a motorbike and now I drive a lot faster!”

PayPal and Wal-Mart have also had high-profile switches to Node.js. Of course, they’re comparing two completely different things to make Node.js look better. In these too-good-to-be-true stories, they’re switching from a gigantic enterprisey codebase to a Node.js app written from scratch. Is there any question that it wouldn’t have been faster? They could have switched to pretty much any anything and gotten a performance gain.

In LinkedIn’s case, they had proxies running on Mongrel with a concurrency of 1. It’s like switching from using one finger to type on a QWERTY keyboard to using ten fingers on a Dvorak keyboard and giving all the credit to Dvorak for a better keyboard layout.

This is classic hype: real-world stories misunderstood and twisted to confuse the unwitting.



Curious to see that most of the comments defending Node seem to follow the same pattern — along the lines of: “But if you use the little-known BeardedHipster.js, or perhaps JoesAsynchLib.js, or, if you’re really in the know, IHave100DownloadsAsynchLib.js, then you no longer have to use .done to avoid eating exceptions. On the other hand be sure not to mix any of these with MarysAsyncLib.js because that depends on the soon-to-be available yield keyword.”

Precisely the sort of duct tape and spit nonsense that gives Node a bad reputation in the first place, and what the author is rightly lambasting.
  • Current Mood: happy happy

Installing and Running node.js applications within IIS on Windows - Are you mad?

http://www.hanselman.com/blog/InstallingAndRunningNodejsApplicationsWithinIISOnWindowsAreYouMad.aspx>Installing and Running node.js applications within IIS on Windows - Are you mad?

Wouldn't it be nice if they just called you back when they were ready?

ASP.NET has always been able to do things (see this MSDN article from 2003 on Async Handlers) with IHttpAsyncHandler but it's always been a bit hard and almost no one knows about it. With the Async CTP and the Task libraries built into .NET, you can build a nicer abstraction on top of IHttpAsyncHandler. Ayende has a simple example AbstractAsyncHandler (there's many of these out there, including a few in our own tools, some things in MVC, and some things in SignalR (more on that soon)) that we can use to do similar work. This example could also do other more complex and pertinent things like file IO, db IO or calling a web service. This is a naive example that doesn't map exactly to the node one below, but it makes the point. Plus, it's nice to look at.

Aside: an ASP.NET IHttpHandler doing the exact same thing on this same machine gets 22,500 requests a second, so node and iisnode has some room to improve, which is great.
  • Current Mood: weak

node.js Is VB6 – Does node.js Suck?

node.js Is VB6 – Does node.js Suck?



Javascript is incredibly ugly. Why would anyone extend it to a full server-side language?
Node.js is single-threaded only. You use non-blocking calls and callback functions. In these days of multicore servers, why would anyone design a language to be only single-threaded? Plus, it’s a PITA to manage all those callback functions and debug.

With Apache, a new thread/process is spawned for each request. The PHP code then runs in that thread. The database calls are blocking calls; the thread sleeps until the call returns. If one thread is waiting for the database, that thread cedes the CPU via UNIX multitasking, and the other threads work.

The drawback is that spawning a thread/process is CPU expensive. (Actually, doesn’t Apache keep a pool of idle threads, only spawning new ones when necessary? If that is true, then the node.js criticism is completely wrong. Node.js’ “single thread model” is based on a criticism of Apache that’s outright false.)

However, unless your website is super-popular, it doesn’t make a difference. I doubt I’ll ever get enough traffic to push the limits of my Linode, even without any WordPress caching extensions.

With node.js, it’s only one thread. Instead of spawning a new thread, you have non-blocking database calls. Then, there’s a callback function when the database call returns. Internally, node.js processes all the callbacks, in order.

There’s another language that uses non-blocking calls and callback functions. It’s VB6 (Microsoft Visual Basic 6). My preliminary analysis of node.js is that it uses advanced VB6-like technology.

Node.js does have a lot of built-in libraries. If you want a basic node.js http server, you just include the http library, listen, and handle the request.

If you want to set up Apache/LAMP, that’s a full day of work. If you write an http server in C++, that’s a lot of code. With node.js’ libraries, you can get a basic http server running quickly.

Do you see the fallacy?

Yes, it’s nice that node.js gets a basic http server running quickly, via nice libraries. However, you still have to write the code for your application.

Clueless people get obsessed with languages and frameworks. No matter what language and framework you use, you have to write your application code. If you use a fancy framework, then you have to write framework-compliant code in addition to your program’s code. With node.js, you’re fiddling around with callback functions and manually managing timing, instead of letting Apache and the OS do it for you.

I wonder if a clueless person prefers to install and run node.js, rather than set up a full LAMP installation? It’s a lot more work to properly install and configure LAMP, than to install node.js and run that.

I suspect that the founders hired a parasite/psychopath to build their product. He’s focusing on hype instead of content, and picked the latest trend, node.js. However, unless I meet their CTO, I don’t know if he’s sane or a psychopath. Given that the non-technical co-founders were intelligent, I’m pretty sure they hired a psychopath.

The “beauty” of node.js is that it only spawns one thread that does everything. However, what if your website is super-popular? What happens once one thread isn’t enough? Then you have to add code to juggle requests between threads and servers. Now, all the advantages of node.js are flushed down the toilet, once one thread can’t handle everything. With Apache, I can upgrade from a 4-core server to an 8-core server and get double the power. You can’t do that with node.js, unless you write code to handle it, which defeats the benefit of using node.js in the first place. Yes, I can write my own thread pooling algorithm, but why not use Apache, which was already super-tuned by others? If I’m balancing my load among several servers, I can directly configure Apache to do that for me. With node.js, wouldn’t I have to manually add all the code for that? (There are some libraries planned but not finished, to address some of my concerns. However, they probably will eliminate any advantages of node.js in the first place.)

Node.js seems like exactly the opposite of the language I’d write. In these days of multi-cores, you need a language that handles multiple cores/threads/processes well. Node.js will only use one core, no matter what you do, unless you spawn multiple node.js instances.
  • Current Mood: weak

Why I think Node.JS is a terrible platform

Статті на сайті (http://www.tuicool.com/articles/hit/IfqQ7z) автора вже немає тому копіюю її текст з http://www.tuicool.com/articles/IfqQ7z



Note: I’ve made some edits about half way through the post


Node.JS is a terrible platform. It’s terribleness stems from a very simple aspect of it, and this aspect happens to be central to how it works: callback-based I/O


I think everyone knows this by now. This way of writing code is terrible.


A few days ago I realized something. After working with Go for a few weeks, I’ve come to like it. Yes, it’s less dynamic than python, and some tasks require more work to get things done (essentially some more boilerplate). There’s much less “magic” available. For instance, there’s no way in Go to provide context-locals as Flask does.


This explicitness in code makes it easier to read code. When there’s less magic, you don’t have to keep as much in your head as you would have to while reading python code.


We can say that there’s some sort of a tradeoff here, you trade some of the expressiveness in exchange for speed and maintainability and peace of mind.


Compare this tradeoff to the one you have to make when you switch from Python to Node.JS


You lose expressiveness, you lose maintainability, you lose peace of mind, and you get speed.


I seriously question whether the “speed” you get with Node.JS is worthwhile, given that you lose both ease of development and ease of maintenance.


I wasted a lot of time trying to learn node and do something useful with it (other than a dumb file server), but couldn’t. I just didn’t really know where to begin.


Usually I’d judge technology based on its own qualities. Is it nice to work with? Does it help me be productive? Is it well documented? Are there resources for help?


Node.JS fails that test. It didn’t make me productive at all. The APIs might have been documented, but it wasn’t clear how to piece things together to make something useful. The async-style of programming is almost entirely inaccessible to my brain. Certainly not a fun way to write programs.


Why did I waste my time with it? Hype (and Hacker News).


I saw people on HN say good things about Node.JS, and I thought: these people are smart and know what they’re talking about, so it must be a good platform.


Unfortunately, it took me several months to realize what a terrible platform it was. I wasn’t really able to produce anything useful on the backend beyond a simple server that serves jade templates and stylus stylesheets.


As soon as I wanted to write any non-trivial code to read stuff from a database and do something with it, I got stumped - I didn’t know how to proceed. I could write some code, but it would turn out very ugly. I couldn’t write code that was pleasing to read (and it certainly wasn’t pleasant to write).


The thing with the node.js ecosystem is that there’s always 3 or more libraries for everything, so when your experience with one library turns out to be not so good, you don’t immediately blame node.js - you blame the library - and you go looking for another one.


I was starting to seriously question my programming abilities!


Of course, some readers might say: we were productive with Node.JS, so this is just you being incompetent.


Alright, I will accept that. I may be stupid in some way that prevents me from being productive using Node.JS, but my point about the tradeoffs still stands: you have to sacrifice both readability and writability with node.js in order to reap the promised “scalability”. This is a terrible, terrible tradeoff.



You can get decent enough scalability even with Python. You have
gevent
, a coroutine based networking library/server. This means that blocking IO is not a problem. The only remaining problem is the python interpreter, which can easily be mitigated by distributing the load across multiple servers (which you will end up doing anyway if you really want to scale).


So what exactly is your excuse for choosing Node.JS as your backend platform?



The only thing that Node.js can do which Python can’t is websockets. Actually I’m not really sure if python can’t do it, some googling suggests that
maybe it can
, after all.



Of course,
Go can do websockets
just fine (
go get code.google.com/p/go.net/websocket
), but that’s besides the point.



Even if we suppose, for argument’s sake, that python can’t do websockets; that’s still not a good reason to write your web app in node.js. You can do the websockets in node.js and the rest of your app in python, as illustrated by
this example
from the Flask project. Yes, this setup (combining python and node) might be a bit convoluted, but it’s still better than actually writing your entire web app in node.js.

  • Current Mood: week

JavaScript це хуйня

Насмикаю коментарів по темі JavaScript для історії (а то раптом все пропаде), для натхнення і для того щоб не забувати. Все взято з https://ebanoe.it/2016/03/04/javascript-for-drivers/.

Все збираюся написати статтю на тему чому ж я ненавиду сайтобудівництво і JavaScript, але то натхнення немає, то слова не клеяться, то здається що все давно написано за мене нічого писати не потрібно і потрібно тільки зібрати посилання.



  1. О, да! Когда Gmail был ещё по инвайтам, только очень ленивый быдлокодер не дрочил на его визуальные свистелки-перделки и не искал (писанные такими же быдлокодерами) статейки по кейворду «AJAX». Впрочем, даже такой аццкий форсинг со стороны Корпораций этому убожеству стать хоть сколько-нибудь удобнее не помог. Но это как PHP (на котором и вот этот самый сайт писан) — «и что, что говно, но миллионы мух не могут быть неправы!»

  2. Все просто:

    1. Язык — фиговый

    2. Все (кроме формошлеперов) это понимают, включая ECMA Script комитет.

    3. Пытаются рихтовать — ES6 Harmony . 7 в разработке

    4. Популярность обусловлена низким уровнем вхождения, даже компилятор не надо ставить, а свистелки — перделки уже можно писать. Все как положено — http://risovach.ru/upload/2014/11/mem/vy-prinyaty_67197431_orig_.jpg

    5. Самое большое преступление — node js. Дали возможность формошлеперам писать код для server side.

    6. G долгое время продвигал https://www.dartlang.org/ и были большие надежды, что он будет нативно исполнятся в chrome

    7. Теперь G спелись с M$ и пилят Type Script, который возможно будет исполнятся нативно в браузерах


    Был краток,
    Овнидий Близкий

  3. Автор справедливо бомбит от JS, только не в ту сторону. Мне после бэкграунда дотнета вообще и десктопных приложений в частности было НИПРИЯТНА ломать свой мозг под этот недоязык. Зато сразу стало очевидным, что jQuery и прочие либы пилят как костыли под JS, правда упоминание этого факта вызывает анальные боли у ДжейЭсоблядков.

  4. Ой, да… кто итерировал по полям объекта в чистом, не приправленном библиотечками джаваскрипте, тот в цирке не смеётся. Сука, хорошую идею — язык с кучей функциональных идиом и асинхронной обработкой событий — ТАК запоганить! Это ж, сука, уметь надо. Лучшее, что в этом смысле было сделано (ИМХО) — это даже не джейквери и прочие мутулз, это компиляция Scala-кода в JS. Потому что в ЖС столько говна и костылей by design, что его можно только заменить на более-менее строгий язык при написании кода, а во что оно там в браузере соберётся — это уже проблемы негров и браузера.

  5. Тайпскрипт не меняет конструкций s1.indexOf(s2) !== -1, кастрированных preg и hasOwnProperty. Какой бы препроцессор ни был, говно by design на входе -> говно by design на выходе.

  6. вы тут блядь пиздохаханьки шутите про жабаскрипт, а вот смотрю как эти хипсторы ссраные с не менее сраными дибилами закачиками вытесняют своими костыльными фреймворками другие ЯПы и у меня яйца седеют от мысли, что возможно придется самому на эту хрень переходить

  7. Если бы вы знали, как меня уже заебали все эти веяния моды, если бы вы знали
    То все кровью ссали по Perl, потом Ruby, потом Python, сейчас вот JS… И это только на уровне языков! По части фреймворков (внутривидовая конкуренция) все еще хуже.
    При этом, орды хомячков толком не научивщись соберать ничего тяжелее Hello World на «выбраном» после очередной хипстерской конфы «модном» языке/фреймворке ломятся «изучать» новый.
    Чуваки, ну мать вашу, научитесь пользоваться профессионально хоть чем-то одним в своей жизни! Потребителю/пользователю/инвестору глубоко настрать насколько модный у вас фреймворк/язык ему нужен хороший продукт, а не то как красиво вы тусовалисьна очередной конференции. Взять тот же Netflix, ребята на каждой конфе рассказывали как делать скалируемую архитектуру и какие они модные, а как только расширился рынок потребителей — так по 3 часа нельзя было зайти/зарегатся потому что сервак лег от перегрузки (скалирование, ага…).


The whole idea behind the post is that I think JavaScript will be dethroned, because there is just too much piled up on top of it.

Web developers writing JavaScript code today don't actually write JavaScript, they use frameworks.

JavaScript has become a DSL factory to some degree.

Why JavaScript Is Doomed

  • Current Mood: anxious anxious