E.g. would legionaries, when faced with a cavalry charge, use pila in place of spears?
Yes, certainly. Strabo mentions that they were used both in hand-to-hand combat and for hurling (Geography 10.1). Plutarch says Antony’s men used them as spears against the Parthians (Marc Antony 45.3). However, the most famous instance which exactly fits your question might be the Battle of Pharsalus. Plutarch claims that Caesar ordered his men not to throw their pila, but to jab them up into the faces of Pompey’s cavalry (Caesar 45):
When the infantry had thus clashed together in the centre and were fighting, Pompey's cavalry rode proudly up from the wing and deployed their squadrons to envelope the enemy's right; and before they could attack, the cohorts ran out from where Caesar was posted, not hurling their javelins, as usual, nor yet stabbing the thighs and legs of their enemies with them, but aiming them at their eyes and wounding their faces. They had been instructed to do this by Caesar, who expected that men little conversant with wars or wounds, but young, and pluming themselves on their youthful beauty, would dread such wounds especially, and would not stand their ground, fearing not only their present danger, but also their future disfigurement. And this was what actually came to pass; for they could not endure the upward thrust of the javelins, nor did they even venture to look the weapon in the face, but turned their heads away and covered them up to spare their faces.
You might notice, however, that Plutarch says that they were normally hurled. So using them as a hand-held spear might have been more unusual.
A very specialised source for the use of this weapon which you might like is Mike Bishop’s The Pilum: The Roman Heavy Javelin. However, this is a very new book and I haven't seen any peer reviews yet, so keep that in mind.