Is there a market for your book?

Writing a book takes hours; perhaps a thousand or more including the research and editing. Needless to say it is a major commitment that authors expect will have a payoff of peer recognition, dissemination of ideas, and (gasp) maybe even a royalty payment. But how do authors know the marketplace wants their book?