This paper reports the measurement of mathrm{J}/{psi } meson production in proton–proton (mathrm {p}mathrm {p}) and proton–lead (mathrm {p}mathrm {Pb}) collisions at a center-of-mass energy per nucleon pair of 5.02,text {TeV} by the CMS experiment at the LHC. The data samples used in the analysis correspond to integrated luminosities of 28,text {pb}^{-1} and 35,text {nb}^{-1} for mathrm {p}mathrm {p} and mathrm {p}mathrm {Pb} collisions, respectively. Prompt and nonprompt mathrm{J}/{psi } mesons, the latter produced in the decay of {mathrm {B}} hadrons, are measured in their dimuon decay channels. Differential cross sections are measured in the transverse momentum range of 2<p_{mathrm {T}} <30{,text {GeV}/{c}} , and center-of-mass rapidity ranges of |y_mathrm{{CM}} |<2.4 (mathrm {p}mathrm {p}) and -2.87<y_mathrm{{CM}}<1.93 (mathrm {p}mathrm {Pb}). The nuclear modification factor, R_{mathrm {p}mathrm {Pb}}, is measured as a function of both p_{mathrm {T}} and y_mathrm{{CM}}. Small modifications to the mathrm{J}/{psi } cross sections are observed in mathrm {p}mathrm {Pb} relative to mathrm {p}mathrm {p} collisions. The ratio of mathrm{J}/{psi } production cross sections in mathrm {p}-going and Pb-going directions, R_mathrm{{FB}}, studied as functions of p_{mathrm {T}} and y_mathrm{{CM}}, shows a significant decrease for increasing transverse energy deposited at large pseudorapidities. These results, which cover a wide kinematic range, provide new insight on the role of cold nuclear matter effects on prompt and nonprompt mathrm{J}/{psi } production.