Using Node.js, you can implement a queue in a few different ways. Here’s a simple way of creating a queue with just JavaScript:
```
class Queue {
constructor() {
this.data = [];
}
This Queue class will have the functions add, remove, and size. We’ll be using an array to store our data. The unshift method inserts the value at the start of the array, ensuring that the first item we added is the last one out. The pop method removes the last item from the array.
A more advanced way to achieve this is by using a library like ‘Bull’. This library allows robust job processing and implements a queue system. Here’s a simple example:
```
const Queue = require(‘bull’);
// Initialize a Queue
const myFirstQueue = new Queue(‘my-first-queue’);
// Add a job to the queue
myFirstQueue.add({ foo: ‘bar’ }).then(() => console.log(‘Job added’)).catch(err => console.log(err));
// Process jobs from the queue
myFirstQueue.process(async(job, done) => {
console.log(job.data); // prints { foo: ‘bar’ }
done();
});
```
This Bull implementation provides more utility such as support for job priorities, job scheduling, etc. But the choice of implementation depends on what level of functionality you’re seeking in your queue.