4 ms·
As you read all these many lines of code to simply find the largest file in a directory, recall that in any language with friendlier blocking/non-blocking seman
by pak 13y ago
As you read all these many lines of code to simply find the largest file in a directory, recall that in any language with friendlier blocking/non-blocking semantics, it could be as simple as (e.g. in Ruby)
Dir.glob('*').select{|f| File.file?(f) }.max_by{|f| File.size(f) }
Plus, the error semantics of this code are sane: if something goes wrong I get an exception I can rescue. If there were no files in the directory, I get nil.
Statting a bunch of files is rarely so costly that parallelism is warranted, unless it is impressed upon you as in Node. The cost in readability and dreaming up generators and promises to solve such a mundane problem is likely much worse. Before you charge headlong into building your next webapp with Node, consider this article food for thought.
- rmgraham 13y agoIt's definitely a trade-off. What Node gives you is async when you need it at the cost of giving you async even when you don't. The pain and constraints introduced by this forced use of async sure has spawned a lot of wheels of all sizes, colours, and compositions.
- sync 13y agoThere's always `fs.readdirSync` etc. node isn't forcing async on you, especially when it comes to file handling.
- jerf 13y agoRuby is the wrong comparison. Write that same code in Go, suitably translated, and it would be fully "async". I hit Go just because it's the most Algol-ish of the sane languages. There's several other options where you just write the code and the compiler and runtime do the async for you.
- ggreer 13y agoIt was a short, simple example to illustrate how yield will improve Node. In real life, you'd probably just do something like: fs.readdirSync(dir).map(function (f) { return { name: f, stat: fs.statSync(path.join(dir, f)) } }).sort(function (a, b) { return b.stat.size - a.stat.size; }); Not going to win any code golf tournaments, but that's JavaScript for you. It was never designed to do this sort of thing. Its strengths lie elsewhere.
- ricardobeat 13y agoIn real life you wouldn't use sync methods, they would destroy your server's performance by blocking the event loop.
- spion 13y agoWith arrow function syntax, extra `maxBy` and `filter` methods on promises for arrays, and nicer file/dir libraries: Dir.glob('*').filter(f => File.isFile(f)).maxBy(f => File.size(f)); Asynchronicity isn't the issue there, the issue is that most JS / node libraries are minimal, not optimized for ergonomic (and of course the verbose lambda syntax)