20 ms·
Node v8.0.0 Released
- bricss 9y agoLong awaited release full of joy!
- petercooper 9y agoFor anyone not in the JS/Node worlds, this is a significant release that people are particularly excited about. It was also delayed somewhat due to wanting to align with V8 which should, however, be totally worth it :-) Other relevant posts digging into new features include http://codingsans.com/blog/node-8 http://codingsans.com/blog/node-8 and https://blog.risingstack.com/important-features-fixes-node-js-version-8/ https://blog.risingstack.com/important-features-fixes-node-j...
- nailer 9y agoShort ver: async await is now in an LTS release of node. Anything that returns a promise can now be run inline - ie, no endless .then() chaining - provided you've started an async context: const writeFile = util.promisify(fs.writeFile), request = util.promisify('superagent'), stat = util.promisify(fs.stat), sorts = require('sorts'), log = console.log.bind(console) const getJeansAndSaveThem = async function(){ var jeans = await request.get('https://example.com/api/v1/product/trousers').query({ label: 'Levi Strauss', isInStock: true, maxResults: 500 }).end() jeans = jeans.sort(sorts.alphabetical) await writeFile('jeans.json', jeans) const status = await stat('jeans.json'); log(`I just got some data from an API and saved the results to a file. The file was born at ${status.birthtime}`) } Note: you should add error handling, I'm new to async/await and this code is to demonstrate a concept on HN, not to run your life support system. ;-)
- AngelloPozo 9y agoAsync await being part of core, not behind a flag, is probably my favorite new addition.
- Etzos 9y agoAsync/await support (without the --harmony flag) was made default in version 7.6 when they updated V8 to version 5.5. The biggest additions here with regard to async/await is the new promisify util and the async_hooks. Edit: Changed wording and included more detail.
- nailer 9y agoOf course, but most people don't run non-LTS node releases :-) Edit: originally wrote 'unstable'. Meant 'non-LTS'
- SparkyMcUnicorn 9y agoNode 7.6 is a stable release. Are you talking about LTS?
- Etzos 9y agoThe 7.6 release was no more unstable than the 8.0 release. Unless you're referring to the fact that 8.0 is going to be a LTS release. But if that's the case, it's not happening for a while yet, 6.10 is still the current LTS version.
- nailer 9y agoYou're right, corrected.
- deleted 9y ago[deleted]
- NoInkling 9y agoAnd some performance improvements. And the fact that there are more to come when they upgrade to V8 5.9 soonish.
- flavio81 9y agoAs noted, this already was possible in Node 7.x. But to use it, you needed a function that returned a promise. And many functions do not, due to having been developed earlier. This is true even for libraries done in 2016. Even today many Node.js developers don't seem to use async/await. At least in my country... And thus they live in braces {} hell. The improvement on the 8.0.0 version is that such an "oldie" function can be Promisified. A great improvement.
- simplify 9y agoBy "oldie" function, do you mean functions that expect node-style callbacks? e.g. function myCallback (err, result) {...}
- styfle 9y agoCorrect. Most node core APIs are written this way and now core ships an utility function[0] to wrap those functions in a promise. [0]: https://medium.com/@styfle/promises-in-node-js-8-x-core-d6a8a93e85a2 https://medium.com/@styfle/promises-in-node-js-8-x-core-d6a8...
- mastax 9y agoIt seems to me that Node should ship promisify-ed versions of all these functions (e.g. fs.readFileAsync). Over time they could replace the implementation with ones that use the OS Async APIs, though perhaps this step is unnecessary if you're already using an event loop underneath.
- lhnz 9y agoUntil then you can use `mz` for a modernised API[0]. [0] https://github.com/normalize/mz https://github.com/normalize/mz
- NoInkling 9y agoI mean, they've been debating about how to add a promisified API for years (see for example https://github.com/nodejs/node/pull/5020 https://github.com/nodejs/node/pull/5020) but nothing has come of it. util.promisify is a welcome addition, but very late for a first step.
- kasbah 9y ago>request = util.promisify('superagent') I don't think that's required. Superagent already returns promises.
- nailer 9y agoAh you're right! https://visionmedia.github.io/superagent/#promise-and-generator-support https://visionmedia.github.io/superagent/#promise-and-genera... Alas too late to edit comment.
- ujal 9y agoThere should also be something like awaitAll to replace await Promise.all calls.
- steve_adams_86 9y agoYou can make it yourself fairly easily I guess: const awaitAll = Promise.all.bind(Promise); async function foo() { var [val1, val2] = await awaitAll([func1, func1]); } It isn't ideal but it's a little cleaner
- nailer 9y ago+1. I'm a big fan of top level function binds to remove boilerplate and keep code readable: const log = console.log.bind(console), query = document.querySelector.bind(document), queryAll = document.querySelectorAll.bind(document);
- RReverser 9y agoYou don't need to bind `console.log` by the way (at least not in any recent version of Node.js or browsers).
- ujal 9y agoawait all([fn1, fn2]) ;) i wonder when we will get s-expressions for function calls (awaitAll [fn1, fn2])
- doublerebel 9y agoJust write (iced) coffeescript, s-exp are totally valid there: https://github.com/nextorigin/riemann-query-parser/blob/master/src/riemann-query.coffee https://github.com/nextorigin/riemann-query-parser/blob/mast...
- ujal 9y agoYeah, s-exps are the only thing I miss :(
- partycoder 9y ago1) This was possible in node 7 2) A request can fail and can timeout. 3) Writing to a file can fail. And you get the idea. Don't omit error handling. Error handling is business logic too. Being relaxed around error handling is the recipe for cascading server failure.
- nailer 9y agoI'm just getting started with async/await (like most people I stick to LTS releases) so please forgive the lack of error handling in the demo code!
- partycoder 9y agoAs someone who spends all day volunteering in Stack Overflow I hope people providing examples were a little bit better at emphasizing error handling. You should see the destructive effects of bad examples there.
- nailer 9y agoYou're welcome to add it.
- ryeguy 9y agoOh please. The point of the post was to illustrate the feature to those wondering "what's async/await?", error handling would be complete noise for that purpose.
- partycoder 9y agoI would argue with you, but I don't really have to prove you wrong. You will eventually prove yourself wrong, since deemphasizing error handling goes wrong very quickly.
- danneu 9y agoIn their snippet, errors would be handled altogether on the promise you get from `getJeansAndSaveThem()`. You don't have enough information to be outraged at the toy example.
- peterparada 9y agoYeah, most of the time, I need to handle errors with try/catch block.
- Rapzid 9y agoIs there a roadmap for supplying async/await interfaces for the entire stdlib? Still some event/callback based stuff in there that doesn't return promises or conform to the callback standard promisfy requires.
- mscdex 9y agoFWIW v8.0.0 is not an LTS release. Technically the first v8.x LTS release will happen in October. See this repo for more details: https://github.com/nodejs/lts https://github.com/nodejs/lts
- nailer 9y agoReplying to myself: since this comment is so popular, here's a fully working version for node 8: const util = require('util'), fs = require('fs'), writeFile = util.promisify(fs.writeFile), request = require('superagent'), stat = util.promisify(fs.stat), sorts = require('sorts'), log = console.log; const getPhotosAndSaveThem = async function(){ try { const response = await request.get('https://jsonplaceholder.typicode.com/photos'); const photos = response.body.sort(sorts.byKey('title')) await writeFile('photos.json', JSON.stringify(photos, null, 2)) const status = await stat('photos.json'); log(`I got some data from an API and saved the responses at ${status.birthtime}`) } catch (e) { log(`Oh no, something went wrong!`, e) } } getPhotosAndSaveThem()
- z3t4 9y agorant: why care about debugability and testability
- cheapsteak 9y ago>node-inspect has been integrated directly into the Node.js runtime Is node-inspect the same thing as node-inspector or something else?
- AngelloPozo 9y agowhen you run something you, can add the --inspect flag to debug. 1. node --inspect app.js 2. In chrome do `about:inspect` you now have debugger attached. WIN!
- jkrems 9y agoDisclaimer: Author of `node-inspect` No, `node inspect` is the new command line debugger for `node --inspect` which replaces `node debug` for `node --debug`. The name is derived from `node --inspect` and has no relation to `node-inspector`.
- nulagrithom 9y agoThanks for your work! CLI has always been my primary method of debugging node, and I'd hate to see it go away. Is this pretty much identical to the old debugger?
- jkrems 9y agoYep, the same commands should still work. There's some additional commands now for CPU/memory profiles. But that's the biggest difference - hopefully.
- flavio81 9y agoFor me, this one brought happiness: Node.js 8.0.0 includes a new util.promisify() API that allows standard Node.js callback style APIs to be wrapped in a function that returns a Promise. An example use of util.promisify() is shown below. This is great stuff. This enables writing code using async and await at all times, which is what any sane developer would do when writing code for Node.js.
- AngelloPozo 9y agoWhat is nice is that it eats into bluebird. I love bluebird, and there are some nice utility functions. But if you only used it to promisify or create promises, there may be no need to keep it.
- Androider 9y agoDoes Node support filtered errors like Bluebird? somePromise.then(function() { return a.b.c.d(); }).catch(TypeError, ReferenceError, function(e) { //Will end up here on programmer error }).catch(NetworkError, TimeoutError, function(e) { //Will end up here on expected everyday network errors }).catch(function(e) { //Catch any unexpected errors }); It's super useful.
- AngelloPozo 9y agoI have not tried, but I would guess no. Why not give it a try and see?
- kkennis 9y agoThe standard way to handle errors coming from 'await' is try/catch, and any errors can be handled in the catch block as if they were coming from a synchronous context. So, you'd now filter async errors the same way you filter synchronous ones.
- Tarean 9y agoLooks really clean. Does bluebird handle this(https://hackage.haskell.org/package/base-4.9.0.0/docs/Control-Exception.html#v:catches https://hackage.haskell.org/package/base-4.9.0.0/docs/Contro...) problem? Sometimes you want to catch two different sorts of exception. You could do something like f = expr `catch` \ (ex :: ArithException) -> handleArith ex `catch` \ (ex :: IOException) -> handleIO ex However, there are a couple of problems with this approach. The first is that having two exception handlers is inefficient. However, the more serious issue is that the second exception handler will catch exceptions in the first, e.g. in the example above, if handleArith throws an IOException then the second exception handler will catch it. Instead, we provide a function catches, which would be used thus: f = expr `catches` [Handler (\ex :: ArithException -> handleArith ex), Handler (\ex :: IOException -> handleIO ex)]
- SparkyMcUnicorn 9y ago"Note that, when referring to Node.js release versions, we have dropped the "v" in Node.js 8. Previous versions were commonly referred to as v0.10, v0.12, v4, v6, etc. In order to avoid confusion with V8, the underlying JavaScript engine, we've dropped the "v" and call it Node.js 8." I was wondering how this would be handled. I guess old habits die hard since this article title includes the "v".
- sigzero 9y agoThat's a dumb reason to drop the "v". smh
- agrippanux 9y agoOdd then that nvm still calls it v8.0.0
- elzi 9y agoI know there's much bigger things in this release to be excited about, but I'm so happy they're allowing trailing commas in function args/params.
- koolba 9y agoCurious why? I get the usefulness for arrays and object declarations. Particular to have cleaner diffs. But why for function calls?
- t1amat 9y agoPrettifying long function signatures and calls. You can spread them across multiple lines with the same trailing comma syntax you might use with a multiline array or object literal.
- epidemian 9y ago> Particular to have cleaner diffs. But why for function calls? Exactly the same reason :)
- koolba 9y agoI suppose but that's usually an indication that an object would be more apt. If you have enough parameters that it needs to be wrapped, they're probably hard to track too.
- 9y ago
- samueloph 9y agoCool! It looks like somebody needs to set up the deb repository for 8.x, the installation script[1] is there, but there's no repo[2] for the node 8.x itself. I also think this[3] url needs to get an update to reflect the new release. edit-> Considering Debian Stretch will be released June 17th, it would be nice to have a repo for this release, i mean ..node_8.x/dists/stretch/Release.. instead of only jessie and sid's. [1]https://deb.nodesource.com/setup_8.x https://deb.nodesource.com/setup_8.x [2]https://deb.nodesource.com/node_8.x/dists/jessie/Release https://deb.nodesource.com/node_8.x/dists/jessie/Release [3]https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions https://nodejs.org/en/download/package-manager/#debian-and-u...
- neovive 9y agoThis is exciting news! I'm a long-time LAMP developer (now mostly Laravel) and have been experimenting with NodeJS for an upcoming API project. As Javascript becomes a larger part of each new project, using one language throughout the entire stack is becoming much more compelling. Is Express still considered the de facto web framework for NodeJS? Or are other frameworks better suited for someone used to the "batteries-included" philosophy of Laravel. I'm watching the new "Learning Node" course from WesBos since he covers async/await and Express seems very similar to most MVC frameworks.
- erulabs 9y agoMight look at Hapi (https://hapijs.com/ https://hapijs.com/) for a more "batteries-included" experience - but Express is still a great choice for just busting out a simple http service.
- Can_Not 9y agoMy passion right now is feathers+nuxt+vuejs. If you're really wanting to keep the "Laravel" feeling though, there is also adonisjs.
- neovive 9y agoAdonisJS is definitely very close to Laravel. I'm not a big fan of the generator syntax, but I assume they will migrate to async/await with the Node v8 announcement.
- deleted 9y ago[deleted]
- neilsimp1 9y agoExpress is still very common, but other than that and Hapi, Sails.js (http://sailsjs.com/ http://sailsjs.com/) is probably a great place to start. It's a full-featured MVC framework built on top of Express.
- drinchev 9y agoExpress is the most popular. As a freelancer I always enjoy when I see express as the framework of choice, since it's very easy to maintain the produced code and is very hard to go unmaintainable. As a matter of fact, what I don't recommend is Sails [1], which tries to do as much as it can and is quite inflexible in terms of technical decisions 1 : http://sailsjs.com http://sailsjs.com
- __s 9y agoLooking forward to writing unit tests for luwa. Node v8.0 should include wasm 1.0
- deleted 9y ago[deleted]
- curiousgal 9y agorant I just finished cleaning my home folder out of the ~100,000 files npm created over the past couple of months. I just build interesting Node projects I come across to check them out and it's gotten that big. I wonder how it's like for regular node devs.
- stocktech 9y agoI cleaned out a random code folder this weekend. Deleted nearly 2 million files from npm.
- simooooo 9y agoI created a barebones vue app and had 12,000 :/
- flavio81 9y agoSadly, this is one of the worst parts of Node.js development. Import one NPM package and it will import hundreds of other packages. The sad thing is that probably many of them are: - no bigger than 50 lines of code - probably "unpromified" - probably unmaintained I really like ECMAScript2016 and the concept behind Node.js, but the NPM ecosystem is really something that isn't pretty.
- Cthulhu_ 9y agoDoesn't the same apply to any nontrivial programming language / dependency management system that works from source? e.g. Go? I mean Maven's repository is usually pretty big too. It's usually compiled .jars but IDE's can opt to download sources + documentation too. A lot of Java applications end up downloading half the internet too. Long story short, any non-trivial development / library / framework / software has a lot of dependencies.
- webXL 9y agoSane dependency management isn't free! I have some tips, though: # find how all node_modules on *nix under the cwd (gsort is for mac with homebrew coreutils; use `sort` otherwise) find . -name "node_modules" -type d -prune -exec du -sh '{}' + | gsort -hr # exclude node_modules from time machine backups mdfind 'kMDItemFSName == node_modules' -0 | xargs -0 tmutil addexclusion
- Matthias247 9y agoThis just motivated me to play around a little bit with JS async/await implementation. What I found interesting is that async functions will always return promises, even if an immediate value could be returned. Like for example in the following function: async function getFromCacheOrRemote() { if (random()) { return "Got it"; } else { await DoSomethingLongRunnning(); return "Got from network"; } } The function will return a Promise independent of which branch is taken, although it could return a string for the first branch. Does anybody know the reason? From a consumer point of view it does not matter if the consumer uses await, since await accepts both immediates and Promises. Is it because always returning promises is more convenient for users which use Promise combinators instead of await and less bug-prone? Or does it maybe even benefit JS runtime optimizations if the returntype is always a Promise - even though the promise in both cases might be of a different subtype? For most applications it probably doesn't matter anyway. However returning and awaiting immediate values eliminates an allocation and eventloop iteration compared to using a Promise, which is helpful for high-performance code. This is why C# now introduced custom awaitables and things like ValueTask<T>.
- qrohlf 9y agoThis "unleashes Zalgo" and is considered a major anti-pattern when designing async APIs: http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony http://blog.izs.me/post/59142742143/designing-apis-for-async...
- ryeguy 9y agoIs it? I only do some moderate node work, so I could be missing the discussion on this, but I've never seen this brought up or talked about before. I read the blog posts, but is this really a sweeping rule in the js community or is it just the opinon of a few people? Because no one seems to be doing it.
- TheAceOfHearts 9y agoIt's a general rule that everyone follows. Things should always be sync or async, not a mix of both.
- p5k 9y agoNotejs should get promise versions of its current callback-based APIs: const fs = require("fs"); fs.writeFile("Hello, World", "helloworld.txt", (error)=>{ if(error) throw error; console.log("done!"); }); Should be: const fs = require("fs"); fs.writeFilePromise("Hello, World", "helloworld.txt").then(()=>console.log("done!"),error=>console.error(error));
- __s 9y agohttps://nodejs.org/api/util.html#util_util_promisify_original https://nodejs.org/api/util.html#util_util_promisify_origina...
- STRML 9y agoThis was tried many years ago. At that time, Promises/A+ was not finalized, and the community could not agree on which Promise specification was best, or even if one was needed at all. Callbacks are lightest-weight re: CPU & memory overhead, so it was decided that core APIs should implement that, and developers can override using promisify (via e.g. Bluebird or the new `util.promisify()`) as they need. But putting that kind of assumption in core could lead to significant pain.
- deleted 9y ago[deleted]
- flavio81 9y agoIt really should be: try{ x = await fs.writeFilePromise("Hello, World", "helloworld.txt") console.log("done!") } catch(error) { console.error(error) // or console.log } This takes advantage of promises fully.
- ianstormtaylor 9y agoDoes anyone have a link to better explanation of the changes to `debugger`? > The legacy command line debugger is being removed in Node.js 8. As a command line replacement, node-inspect has been integrated directly into the Node.js runtime. Additionally, the V8 Inspector debugger, which arrived previously as an experimental feature in Node.js 6, is being upgraded to a fully supported feature. It sounds like `node debug` will no longer work? But it is replaced with something that's better? What is `node-inspect` and where can I learn about it?
- rattray 9y agoGood questions – the new facilities are improvements AFAICT: node --inspect index.js Or node --inspect --debug-brk index.js then open `chrome://inspect` in Chrome. https://medium.com/@paul_irish/debugging-node-js-nightlies-with-chrome-devtools-7c4a1b95ae27 https://medium.com/@paul_irish/debugging-node-js-nightlies-w...
- sigil 9y agoCan I debug node 8 from the command line, or do I need X / chrome now?
- rattray 9y agoYou can also debug, to a limited degree, from the command line: https://nodejs.org/api/debugger.html https://nodejs.org/api/debugger.html > Node.js's debugger client is not a full-featured debugger, but simple step and inspection are possible.
- sigil 9y agoThanks. I use the REPL debugger often, glad to see it's not going away.
- NoInkling 9y agoNote: --debug-brk has been deprecated in Node 8, you can use --inspect-brk (--inspect not needed) instead.
- STRML 9y agoThis is a big release. Async/await in stable core is something I've been (literally) waiting 6 years for. Many people have criticized Node's cooperative multithreading model, with both good and uninformed reasons. Yet, it is without dispute that the model is popular. Async/await is a giant leap forward toward making Node usable for beginner and expert alike. This release is a celebration. For those of you with existing applications looking to migrate, try `--turbo --ignition` to emulate (most) of the V8 5.9 pipeline. Anecdotally, microbenchmark-style code regresses slightly, real-world code improves by as much as 2x. Exciting times.
- rattray 9y ago> Anecdotally, microbenchmark-style code regresses slightly, real-world code improves by as much as 2x. Curious, any hunches as to why?
- STRML 9y agoWell, the optimizing pipeline has completely changed in V8 5.8 (if you use `--turbo --ignition`) and in 5.9+. It's been simplified and most importantly, does not deoptimize on quite so many common features (such as try/catch). More information at http://benediktmeurer.de/2017/03/01/v8-behind-the-scenes-february-edition/ http://benediktmeurer.de/2017/03/01/v8-behind-the-scenes-feb... and some of his other articles. In my testing it appears that TurboFan cannot optimize certain patterns as well as Crankshaft did, but there's no reason to believe those regressions will remain as TF evolves. Optimizing more code is much more important for real apps.
- k__ 9y agoThe promisify stuff looks rather clunky. Aren't there better options?
- ryeguy 9y agoThat's only needed to convert old callback style code to promise-compatible code. Most libraries either return promises now or have an option to, so this isn't necessary.
- riccardomc 9y agoIt really is a significant release: the world 'significant' is used in 7 of the first 13 lines of the release statement. http://imgur.com/a/F572e http://imgur.com/a/F572e