GithubHelp home page GithubHelp logo

packtpublishing / node.js-design-patterns-third-edition Goto Github PK

View Code? Open in Web Editor NEW
1.4K 52.0 445.0 1.21 MB

Node.js Design Patterns Third Edition, published by Packt

Home Page: https://www.nodejsdesignpatterns.com/

License: MIT License

JavaScript 98.17% HTML 1.79% Dockerfile 0.04%
nodejs node node-js book books patterns design-patterns javascript examples

node.js-design-patterns-third-edition's Introduction

Node.js Design Patterns - Third-Edition

Node.js Design Patterns Third Edition (published by Packt), A book by Mario Casciaro and Luciano Mammino

Solutions for exercises

If you have completed one of the exercises and want to share your solution or if you are looking for ideas on how to solve one of the exercises, check out our Exercises Solutions wiki page.

Discussion board

If you are currently reading the book and want to engage with other readers, we have created a Node.js Design Patterns Discussion Board on GitHub. You are welcome to join the community!

Support this book

A book is a work of art and passion. We invested a lot of our time and tried our best to create a great book and we hope we managed to give you something valuable with our efforts. If you enjoyed this book, here are some ways you can help us to spread the word and support our work:

THANK YOU ❤️

node.js-design-patterns-third-edition's People

Contributors

dependabot[bot] avatar dnafication avatar kishorrit avatar lmammino avatar mariocasciaro avatar mfeyx avatar packt-itservice avatar pallavjha avatar roboli avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node.js-design-patterns-third-edition's Issues

return/no return in parseJSON example

Under the section heading Propagating errors, the readJSON function returns callback(err) in two places, but does not return callback(null, parsed) (the non-error case). The text does not seem to explain why the return is needed in the error cases but not in the non-error case.

Interpretation of figure 4.3

Hi. The figure 4.3 and its explanation is very confusing, at least for me.

  1. When the asynchronous operation of Task 1 is completed, the event loop gives control to it. When Task 1 completes its internal synchronous processing as well, it notifies the Main function.
  1. When the asynchronous operation triggered by Task 2 is complete, the event loop invokes its callback, giving control back to Task 2. At the end of Task 2, the Main function is notified once more. At this point, the Main function knows that both Task 1 and Task 2 are complete, so it can continue its execution or return the results of the operations to another callback.

How does task 2 or task 3 notify the Main function? Once the Main function runs task 1 and task 2 it terminates its execution stack and everything from that point will be called from event loop. Main function cannot be recalled from dead and ... can continue its execution or return the results of the operations to another callback.

So do authors mean with "notify Main function"?

Changes in 3rd edition

Hey

I've the 2nd edition of this great book, And I haven't still finished it. I saw this 3rd edition recently and I'm starting to feel I'll miss a lot of new material lol.

Could you share what new material has been added to this edition of the book?

Question on 11-asyncawait-web-spider-v4

Hope you don't mind asking questions about your new book (Node.js Design Patterns)...
Don't know another way of reaching out to you.
Node.js processing model is all new to me, and my mind is bent while trying to follow the examples, especially the one here:

https://github.com/PacktPublishing/Node.js-Design-Patterns-Third-Edition/tree/master/05-asynchronous-control-flow-patterns-with-promises-and-async-await/11-asyncawait-web-spider-v4

In file TaskQueuePC.js, line 44, the consumer function is invoked by passing "taskWrapper" as the argument.
However, line 12 defines the consumer() function without any arguments.
I can't see how the consumer function would as defined in line 12 relates to how it's invoked in line 44.

Thanks,

Julius Lerm
Chicago, IL

Question about spider version 3 example in the Asynchronous Control Flow Patterns with Callbacks

In the Web spider version 3 code example (Asynchronous Control Flow Patterns with Callbacks) chapter, The author defined a done callback (will be called asynchronously by the spiderLinks function).

function done (err) {
  if (err) {
    hasErrors = true
    return cb(err)
  }
  if (++completed === links.length && !hasErrors) {
    return cb()
  }
}

The author mentioned that:

The hasErrors variable is necessary because if one parallel task
fails, we want to immediately call the callback with the given error.
Also, we need to make sure that other parallel tasks that might still
be running won't invoke the callback again.

I read done definition multiple times, and think that the !hasErrors check is not need in the ++completed === links.length && !hasErrors) because if we have at least one error (in one of the concurrent functions) ++completed will not be reached in that function, so the completed === links.length will never be satisfied. so probably we need to check !hasErrors in:

  if (err && !hasErrors) {
    hasErrors = true
    return cb(err)
  }

To avoid calling the callback with error multiple times.

Release date?

Hi, when do you expect to release the new version of the book?

I'm curious because now I' m reading second edition and that's really awesome, but some things a bit outdated (like babel for async await, etc). So I'm really looking forward for the new edition ;)

P.S. @mariocasciaro , Thank you for the great book!
@packt-it thank you for publishing this book ;)

About errata in Node.js Design Patterns, 3rd. edition

Dear Mario & Luciano,

I am including here an excerpt from a message I sent to Packt Publishing a few days ago.... They told me that the only way to handle the errata was to use their form, or open an issue in the GitHub repository.

I've tried to get informatión about errata in the book "Node.js design patterns", and there was no luck. I can send errata in https://www.packtpub.com/support/errata , but I can't find a page with confirmed errata or possible errata.

I'm trying to get information similar to what I can find in O'Reilly books. You can see an example here: https://www.oreilly.com/catalog/errata.csp?isbn=9781449392680

The buyers of a book should have information about errata in the books we have bought. It is a loss of valuable information not to have that information. If you don't make available that information, a buyer can't know whether some part of the book is wrong (my printed book will never be updated, even when updated editions can fix the errata). When there is no page for errata in a book, how can I decide if it is worth sending the errata I have found? Do you want everyone who finds errata to lose their time sending you erratas you already know?

Do you plan to make a page to collect the detected bugs, like O'Reilly does?

Mario / Luciano, thank you very much for writing this book. I hate Node.js, but I love your book, which is very very very very good. And I keep recommending it to my colleagues and friends who use Node.js.

Now, some typos (or possible typos) in the printed version of third edition:

  • In page 185-186, there is no coherence in the positions of read. It's supposed that Transform stream is a particular case of Duplex stream, so the read function should be in the same position (it seems that the right one is the one in Figure 6.5.
  • In the second line of page 191, appears "Italy." where it should say "Italy".
  • In page 205, there is a mention to (a literal) cb() function, but that doesn't exist in the code of page. Do you mean the callback function of finish handler?
  • In page 498, the line with worker.disconnect() is marked with // (2) instead of the right way: // (3).

Kind regards,
Oscar

No need to promisify mkdirp when using it's lastest version

I tried to replicate your code chapter by chapter and I wanted to use the latest version of mkdirp dependency.

I've come to find that doing promisify(mkdirp) with the latest version of mkdirp (1.0.4) gives us the following error:

TypeError: invalid options argument

It appears that the new version of mkdirp already returns a promise, so no need to do promisify(mkdirp) no more.

Question on 05-asynchronous-control-flow-patterns-with-promises-and-async-await/03-promises-web-spider-v2

Hello Mario & Luciano,

I hope you don't mind me asking a question about your new book "Node.js Design Pattern" Third Edition. I've been looking for ways to reach out to you.

I've been studying Node.js for some time now, I must admit that the level of the book is tiny a bit high, but I am keeping up.

When I follow the example in 05-asynchronous-control-flow-patterns-with-promises-and-async-await/03-promises-web-spider-v2 I got an error when I use the latest version of mkdirp which is version "^1.0.4".

I am getting an error on line 16 of the spider.js module.

return mkdirpPromises(dirname(filename))

Here are the details of the error

TypeError: invalid options argument
at optsArg (/Users/eagboka/Documents/GitHub/promises-web-spider-v2/node_modules/mkdirp/lib/opts-arg.js:13:11)
at mkdirp (/Users/eagboka/Documents/GitHub/promises-web-spider-v2/node_modules/mkdirp/index.js:11:10)
at /Users/eagboka/Documents/GitHub/promises-web-spider-v2/lib/internal/util.js:360:7
at new Promise ()
at mkdirp (/Users/eagboka/Documents/GitHub/promises-web-spider-v2/lib/internal/util.js:346:12)
at /Users/eagboka/Documents/GitHub/promises-web-spider-v2/spider.js:16:20
at processTicksAndRejections (node:internal/process/task_queues:96:5) {stack: 'TypeError: invalid options argument
at op…ions (node:internal/process/task_queues:96:5)', message: 'invalid options argument'}

But when I use "mkdirp" version 0.5.1 I don't get the error and everything works fine.
Wouldn't there be a way to solve this problem or else we are condemned to use version 0.5.1 of this module?

Thanks,
Sandro Agboka
OpenTech-Consult
Lomé, Togo

Wrong URL in the README for the solution wiki

The link to Exercises Solutions wiki page currently points to https://github.com/PacktPublishing/Node.js-Design-Patterns-Third-Edition/wiki/Node.js-Design-Patterns-Third-Edition---Exercises-Solutions, however, it should point to https://github.com/PacktPublishing/Node.js-Design-Patterns-Third-Edition/wiki/Node.js-Design-Patterns-Third-Edition---Exercise-Solutions

These are two wiki with very similar names:
image

The first one actually contains the solutions whereas the second one is blank.

Question about 06-Coding-with-Streams Multiplexing

Hi there, I'm reading multiplexing in Chapter 6, and I ran into a problem that I can't figure out.
First I copied the contents of the client.js and server.js into my local file, but instead use file read/write stream rather than stdout or stderr, and the code runs smooth without any problem. The complete code is shown below:

// client.mjs
import { connect } from 'net'
import { createReadStream } from 'fs'

function multiplexChannels (sources, destination) {
  let openChannels = sources.length
  for (let i = 0; i < sources.length; i++) {
    sources[i]
    .on('readable', function () { // ①
      let chunk
      while ((chunk = this.read()) !== null) {
        const outBuff = Buffer.alloc(1 + 4 + chunk.length) // ②
        outBuff.writeUInt8(i, 0)
        outBuff.writeUInt32BE(chunk.length, 1)
        chunk.copy(outBuff, 5)
        console.log(`Sending packet to channel: ${i}`)
        destination.write(outBuff) // ③
      }
    })
    .on('end', () => { // ④
      if (--openChannels === 0) {
        destination.end()
      }
    })
  }
}

const socket = connect(3000, '127.0.0.1', () => {
+  const sourceFiles = [
+   createReadStream('/Users/cuishimin/Documents/space/ndp/client.mjs'),
+    createReadStream('/Users/cuishimin/Documents/space/ndp/server.mjs'),
+ ]

  multiplexChannels(sourceFiles, socket)

})
// server.mjs
import { createWriteStream } from 'fs'
import { createServer } from 'net'
import { resolve } from 'path'

function demultiplexChannel (source, destinations) {
  let currentChannel = null
  let currentLength = null

  source
    .on('readable', () => { // ①
      let chunk
      if (currentChannel === null) { // ②
        chunk = source.read(1)
        currentChannel = chunk && chunk.readUInt8(0)
      }

      if (currentLength === null) { // ③
        chunk = source.read(4)
        currentLength = chunk && chunk.readUInt32BE(0)
        if (currentLength === null) {
          return null
        }
      }

      chunk = source.read(currentLength) // ④
      if (chunk === null) {
        return null
      }

      console.log(`Received packet from: ${currentChannel}`)
      destinations[currentChannel].write(chunk) // ⑤
      currentChannel = null
      currentLength = null
    })
    .on('end', () => { // ⑥
      destinations.forEach(destination => destination.end())
      console.log('Source channel closed')
    })
}

const server = createServer(socket => {
+  const destFiles = [
+   createWriteStream('/tmp/filetcp/1.txt'),
+   createWriteStream('/tmp/filetcp/2.txt'),
+  ]

  demultiplexChannel(socket, destFiles)
})
server.listen(3000, () => console.log('Server started'))

But when I add highWaterMark option to file read stream of client.mjs like below:

-const sourceFiles = [
-    createReadStream('/Users/cuishimin/Documents/space/ndp/client.mjs'),
-    createReadStream('/Users/cuishimin/Documents/space/ndp/server.mjs'),
-  ]
+ const sourceFiles = [
+    createReadStream('/Users/cuishimin/Documents/space/ndp/client.mjs', { highWaterMark: 8 }),
+    createReadStream('/Users/cuishimin/Documents/space/ndp/server.mjs', { highWaterMark: 8 }),
+  ]

and run client.mjs again, something strange happened: both client and server socket hang forever. And the content of the server-generated file is incomplete, eg. 1.txt has partial content of client.mjs in this case.

I know that hightWaterMark is the maximum number of bytes of the internal buffer, but I can't figure out this has something to do with the problem, is there something that I missing?

FailSafeSocket doesn't change from online to offline

Hi,
I ran client and server in 09-behavioral-design-patterns/02-state-failsafe-socket directory and It seems that FailSafeSocket never changes from online to offline state. We need some code in _safeWrite method in OnlineState to change state to offline if error happens.

$5 campaign?

Hey guys! Curious about how to access the book for just $5. I do not see any options stating we can buy it for $5, rather the retail price of 49.99 or 5 payments of $5 for a 5 month subscription, which technically isn't us owning the book. That's a $25 rental fee.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.