At first glance, earthworms appear to have little awareness of the world around them. They appear to be little more than living pink tubes, without eyes or ears to tell them where they are. However, earthworms are well adapted to an underground life, and have developed special senses to keep them from dangerous conditions--like the light of day.
If you could find the "head" section on an earthworm and knew what to look for, you might be able to identify sections of tissue with tiny specialized structures which enable an earthworm to detect light. These do not give an earthworm vision as we know it, only the ability to detect degrees of brightness.
Earthworms are adapted to living in cool, dark places, and seek them out. Because earthworms have no lungs, but respire through their skin, they need to keep themselves moist. The rich soils through which they burrow are ideal conditions for this.
When an earthworm is exposed to the sunlight, perhaps by a gardener's errant shovel blade, or an animal digging, it will almost immediately attempt to writhe its way back into the soil. If an earthworm is exposed to the sun for too long, it will begin to dehydrate. Prolonged exposure to the sun will result in paralysis. The earthworm's "eyes" enable it to sense such dangerous conditions.
Earthworms will voluntarily venture above ground in certain conditions, especially if there has been a heavy rainfall. Excess moisture can flood earthworm tunnels and cause them to drown. Venturing above ground during the day in such instances is generally safe for an earthworm, since the air is moist and the sun is obscured by cloud cover. Earthworms will also commonly surface at night, when the air is cooler.
The best way to observe earthworms at night or in a worm composting box is to use a light with red cellophane or red plastic taped over it. Worms cannot tolerate ultraviolet light, but are less sensitive to dim or restricted light.