NYPD Officer Ryan Nash was out on a routine call — to locate an emotionally disturbed person — when suddenly he came face to face with a terrorist committing the worst massacre in New York City in years.

Nash, 28, who is stationed in the 1st Precinct, stopped the killing spree by shooting Sayfullo Saipov near Stuyvesant High School at Chamber and West streets on Tuesday, police sources said.

Saipov shouted “Allahu akbar!” — Arabic for “God is great!” — after allegedly ramming a Home Depot rental pickup truck into people along a bike path, killing eight. He then whipped out two weapons — which turned out to be a paintball gun and a pellet gun — as he ran from his smashed truck.

Nash gave chase, drew his weapon and opened fire, bringing down the 29-year-old suspect before he could do any more harm, law enforcement sources said.

Nash, who lives in Medford, Long Island, was taken to Bellevue Hospital, where he was treated for ringing in his ears.

The fast-acting cop has been on the job for more than five years with more than 50 arrests to his credit, sources said.

“A uniformed police officer . . . confronted the subject and shot him in the abdomen,” NYPD Commissioner James O’Neill said.