Where the P2SH script gets written?
The script is maintained by the intended recipient; he is the one responsible to keep it and not to lose it. The nodes do not store any database of the scripts.

The script is provided by the spender upon spending the p2sh as part of the scriptSig data. For the exact specification of how this data is structured, see BIP 16 by Gavin Andresen. This allows the other nodes to validate that the script was redeemed correctly.

The purpose of p2sh is not to limit the data on the blockchain – that remains the same. It is, as per the BIP, to "move the responsibility for supplying the conditions to redeem a transaction from the sender of the funds to the redeemer".