File tree Expand file tree Collapse file tree 2 files changed +15
-13
lines changed
Expand file tree Collapse file tree 2 files changed +15
-13
lines changed Original file line number Diff line number Diff line change 33 "version" : " 1.0.0" ,
44 "description" : " A simple example to demonstrate how to use callback in JavaScript using image element" ,
55 "scripts" : {
6- "start" : " live-server"
6+ "start" : " live-server" ,
7+ "catch-them-all" : " node scripts/catch-them-all.js"
78 },
89 "repository" : {
910 "type" : " git" ,
Original file line number Diff line number Diff line change 11const http = require ( 'http' )
22const fs = require ( 'fs' )
3+ const path = require ( 'path' )
4+
5+ function getImagePath ( pokemonNumber ) {
6+ return path . join ( __dirname , `../images/pokemons/${ pokemonNumber } .png` )
7+ }
38
49function catchPokemon ( pokemonNumber ) {
510 const options = {
@@ -10,25 +15,21 @@ function catchPokemon(pokemonNumber) {
1015
1116 http . get ( options , function ( response ) {
1217 if ( response . headers [ 'content-type' ] != 'image/png' ) {
13- return undefined
18+ return
1419 }
1520
1621 let chunks = [ ]
17- response . on ( 'data' , ( chunk ) => chunks . push ( chunk ) )
22+ response . on ( 'data' , chunk => chunks . push ( chunk ) )
1823
1924 response . on ( 'end' , ( ) => {
2025 const buffer = Buffer . concat ( chunks )
21- fs . writeFile (
22- `../images/pokemons/${ pokemonNumber } .png` ,
23- buffer ,
24- ( error ) => {
25- if ( error ) {
26- console . log ( `Missed Pokemon #${ pokemonNumber } ` )
27- return
28- }
29- console . log ( `Caught Pokemon #${ pokemonNumber } ` )
26+ fs . writeFile ( getImagePath ( pokemonNumber ) , buffer , error => {
27+ if ( error ) {
28+ console . log ( `Missed Pokemon #${ pokemonNumber } ` )
29+ return
3030 }
31- )
31+ console . log ( `Caught Pokemon #${ pokemonNumber } ` )
32+ } )
3233 } )
3334 } )
3435}
You can’t perform that action at this time.
0 commit comments