🎨Generating Images with DALL·E and Node.js


We’ve already built text-based AI apps in Day 1 & 2.
Now it’s time to let AI create images for us, using OpenAI’s DALL·E API and Node.js.
🎯 What We’re Building
A Node.js script that:
Accepts a text prompt
Sends it to DALL·E
Saves the generated image to your local machine
🛠 Setup
Install dependencies:
npm install openai dotenv axios
💻 Code – image-gen.js
const { Configuration, OpenAIApi } = require("openai");
const axios = require("axios");
const fs = require("fs");
require("dotenv").config();
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
async function generateImage(prompt) {
try {
const response = await openai.createImage({
prompt,
n: 1,
size: "1024x1024",
});
const imageUrl = response.data.data[0].url;
console.log("🖼 Image URL:", imageUrl);
// Save image locally
const img = await axios.get(imageUrl, { responseType: "arraybuffer" });
fs.writeFileSync("generated.png", img.data);
console.log("✅ Image saved as generated.png");
} catch (error) {
console.error("❌ Error:", error.message);
}
}
generateImage("A cyberpunk city skyline at night in neon colors");
🧪 How to Run
node image-gen.js
This will:
Send your prompt to DALL·E
Print the image URL
Save it as
generated.png
locally
🔍 What You Learned Today
✅ How to generate images with OpenAI’s DALL-E API
✅ How to download files from a URL with axios
✅ How to save binary data to disk with fs
Subscribe to my newsletter
Read articles from Anuj varshney directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Anuj varshney
Anuj varshney
Hey, I am Anuj Varshney a software developer with over a year of experience at iQuinceSoft Pvt Ltd, specializing in web development using various programming languages and tools. He holds a Bachelor of Computer Application degree from Dr. BR Ambedkar University and is currently pursuing a Master of Computer Application from Chandigarh University via distance learning. Anuj has worked on a variety of projects, including the maintenance and updates of CaritasRevolution.com, iQuinceSoft.com, and OdontologiaVejarno.com. His skills include proficiency in programming languages such as JavaScript, C++, C, HTML, and CSS, as well as front-end development using React.js and Nuxt.js. He is also familiar with Node.js, Express.js, MongoDB, and various other tools such as WordPress REST API, Firebase, Redux, Stripe, and Material UI. Anuj is a quick learner with strong analytical skills, and attention to detail, and is committed to delivering high-quality work within tight deadlines.