Can anyone tell me how to do that and give me the code for it.
It is no different than for an Arduino Uno.
You do have a 3.3V power source right?
I have project of Arduino Nano connected with ESP8266 board.
If you connect VCC of ESP8266 direct to Nano board.
You will have a problem of current consumtion not enough for ESP.
I try to use external VCC from regulator IC, such LM7805.
That's work and no any problem.
Arduino Nano is 5V board. ESPs are strictly 3.3V boards, even at the signal level for their RX/TX lines.
Also, for the correct operation of the ESP you should do the following: RST - pullup 10K to 3.3V, CH_PD - pullup 10K to 3.3V, GPIO0 - pullup 10K to 3.3V (otherwise it goes into burn loader mode), GPIO2 - pullup 10K to 3.3V.
Make sure that Vcc operates at 3.3V also. Put a voltage divider (10K/22K) at least at the ESP's RX line.
AND, if you power both of them from the different sources - DO NOT FORGET to connect the grounds.
ESPs, mostly, operate at 115200 baud - remember that too.
Tell me how it goes.
I used to connect the esp this way but dont know why it is not working correctly
That is because CH_PD, RST, GPIO0 and GPIO2 are not pulled up high.