Is your application slowing down under the weight of heavy, long-running tasks? Operations like generating reports, sending bulk emails, or processing large images can block your main thread, leading to a sluggish user experience. The solution is to offload these operations to a background worker, allowing your application to stay fast and responsive.
This is where worker.do comes in. We provide a simple, powerful API to manage background jobs, task queues, and asynchronous processing without the headache of managing your own infrastructure.
In this tutorial, we'll walk you through the entire process of enqueueing your very first asynchronous job using Node.js and the worker.do SDK. You'll be surprised how quickly you can improve your application's performance.
Before we begin, make sure you have the following:
First, let's create a new directory for our project and initialize it with npm. Open your terminal and run the following commands:
mkdir my-worker-app
cd my-worker-app
npm init -y
This creates a new folder, navigates into it, and generates a package.json file with default settings.
To interact with the worker.do API, you'll need our official SDK. Install it using npm:
npm install @do/sdk
This package provides everything you need to connect to our service and manage your job processing queue.
Now for the fun part! Create a new file in your project directory named enqueueJob.js. This script will be responsible for sending a new task to our background worker queue.
Paste the following code into enqueueJob.js:
import { Worker } from '@do/sdk';
// It's best practice to store your API key in an environment variable
const apiKey = process.env.WORKER_DO_API_KEY;
if (!apiKey) {
console.error('Error: WORKER_DO_API_KEY environment variable not set.');
process.exit(1);
}
// Initialize the worker service with your API key
const worker = new Worker(apiKey);
async function main() {
// Define the task payload - this is the data your worker will process
const payload = {
userId: 'usr_1a2b3c',
reportType: 'monthly_sales',
format: 'pdf'
};
try {
// Enqueue a new job to be processed asynchronously
const job = await worker.enqueue({
queue: 'reports', // The queue to send the job to
task: 'generate-report', // The specific task to be executed
payload: payload, // The data for the task
retries: 3 // Automatically retry up to 3 times on failure
});
console.log(`Job ${job.id} has been successfully enqueued.`);
console.log('Your main application can now continue without waiting!');
} catch (error) {
console.error('Failed to enqueue job:', error);
}
}
main();
Let's break down what's happening here:
To run the script, you first need to set your API key as an environment variable.
On macOS/Linux:
export WORKER_DO_API_KEY='YOUR_API_KEY'
node enqueueJob.js
On Windows (Command Prompt):
set WORKER_DO_API_KEY=YOUR_API_KEY
node enqueueJob.js
Replace 'YOUR_API_KEY' with the actual key from your worker.do dashboard.
When you run the command, you should see the success message almost instantly:
Job job_xxxxxxxxxxxx has been successfully enqueued.
Your main application can now continue without waiting!
Congratulations! You've successfully offloaded a task. Your Node.js script finished immediately, but the job is now securely in the worker.do queue, waiting to be processed by our scalable infrastructure. Your application is free to handle the next user request.
Once your job is enqueued, the worker.do platform takes over:
Enqueueing a single job is just the beginning. With worker.do, you can build sophisticated, reliable workflows:
You've taken the first step toward building faster, more reliable, and more scalable applications. By offloading heavy lifting to a dedicated background job processor like worker.do, you ensure a great user experience while we handle the infrastructure.
Ready to take the next step? Explore our documentation or log in to your dashboard to see your new job