How did writing and literature come into being?
Many historians concur that writing came into existence in Mesopotamia in the fourth millennium BCE, although isolated texts from Greece, Romania, Egypt, and China from the sixth millennium BCE are also under consideration. Ultimately, the exact point of origin of writing is less important than the fact that the most substantial evidence we have of early writing systems is from Mesopotamia (current Iraq) and that early writing was designed as a means of accounting for agricultural goods, not for literature. Writing comes into being as technology designed for accounting and supply maintenance. Its adaptation for literary purposes is much later; one thinks, for example, of the Middle Babylonian Epic of Gilgamesh of the Egyptian texts pertaining to the afterlife.
Literature, it should be stressed, has its roots in oral tradition, not in writing. In the context of Ancient Greece, for example, the oral traditions that would later be codified into the written Homeric epics were maintained through memory and song, not through textuality. As early as the eighth century BCE (some scholars point toward the seventh century BCE instead), writing had come into play not only in Ancient Greece but in Ancient Israel as well, as demonstrated by some of the earliest prophetic texts. Writing, then, shows up in the Ancient near the eastern and later pan-Mediterranean environment for varied purposes, including the singing of laws. Singing the laws enabled the largely illiterate populace to memorize the dicta of the law, by virtue of meter and stock, idiomatic phrasing.
Poetry, and indeed "literature" as such, is a late development in the career of written language. We should look first to priestly book-keeping, agriculture, accounting, and the law before we look to writing in the context of literature. To be sure, writing is prominently known for its literary role today, but at its inception, it was a working technology employed by priestly record-keepers and lawmakers.