Flash memories and semiconductor p-n junctions are two elementary but incompatible building blocks of most electronic and optoelectronic devices. The pressing demand to efficiently transfer massive data between memories and logic circuits, as well as for high data storage capability and device integration density, has fueled the rapid growth of technique and material innovations. Two-dimensional (2D) materials are considered as one of the most promising candidates to solve this challenge. However, a key aspect for 2D materials to build functional devices requires effective and accurate control of the carrier polarity, concentration and spatial distribution in the atomically thin structures. Here, a non-volatile opto-electrical doping approach is demonstrated, which enables reversibly writing spatially resolved doping patterns in the MoTe2 conductance channel through a MoTe2/hexagonal boron nitride (h-BN) heterostructure. Based on the doping effect induced by the combination of electrostatic modulation and ultraviolet light illumination, a 3-bit flash memory and various homojunctions on the same MoTe2/BN heterostructure are successfully developed. The flash memory achieved 8 well distinguished memory states with a maximum on/off ratio over 104. Each state showed negligible decay during the retention time of 2,400 s. The heterostructure also allowed the formation of p-p, n-n, p-n, and n-p homojunctions and the free transition among these states. The MoTe2 p-n homojunction with a rectification ratio of 103 exhibited excellent photodetection and photovoltaic performance. Having the memory device and p-n junction built on the same structure makes it possible to bring memory and computational circuit on the same chip, one step further to realize near-memory computing.