Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Examples of Golang compared to Node.js for learning 🤓 By@miguelmota

License

NotificationsYou must be signed in to change notification settings

miguelmota/golang-for-nodejs-developers

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation


logo


Golang for Node.js Developers

Examples ofGolang examples compared toNode.js for learning

LicenseMentioned in Awesome GoPRs Welcome

This guide full of examples is intended for people learning Go that are coming from Node.js, although the vice versa can work too. This is not meant to be a complete guide and it is assumed that you've gone through theTour of Go tutorial. This guide is meant to be barely good enough to help you at a high level understand how to doX inY and doing further learning on your own is of course required.

Contents

Examples

All sample code is available inexamples/

comments


Node.js

// this is a line comment/* this is a block comment*/

Go

package mainfuncmain() {// this is a line comment/*   this is a block comment*/}

⬆ back to top

printing


Node.js

console.log('print to stdout')console.log('format %s %d','example',1)console.error('print to stderr')

Output

print to stdoutformat example 1print to stderr

Go

package mainimport ("fmt""os")funcmain() {fmt.Println("print to stdout")fmt.Printf("format %s %v\n","example",1)fmt.Fprintf(os.Stderr,"print to stderr")}

Output

print to stdoutformat example 1print to stderr

⬆ back to top

logging


Node.js

console.log((newDate()).toISOString(),'hello world')

Output

2021-04-11T20:55:07.451Z hello world

Go

package mainimport"log"funcmain() {log.Println("hello world")}

Output

2021/04/11 13:55:07 hello world

(Packagelog writes to standard error ánd prints the date and time of each logged message)

⬆ back to top

variables


Node.js

// function scopedvarfoo='foo'// block scopedletbar='bar'// constantconstqux='qux'

Go

(variables are block scoped in Go)

package mainfuncmain() {// explicitvarfoostring="foo"// type inferredvarbar="foo"// shorthandbaz:="bar"// constantconstqux="qux"}

⬆ back to top

interpolation


Node.js

constname='bob'constage=21constmessage=`${name} is${age} years old`console.log(message)

Output

bob is 21 years old

Go

package mainimport"fmt"funcmain() {name:="bob"age:=21message:=fmt.Sprintf("%s is %d years old",name,age)fmt.Println(message)}

Output

bob is 21 years old

⬆ back to top

types


Node.js

// primitivesconstmyBool=trueconstmyNumber=10constmyString='foo'constmySymbol=Symbol('bar')constmyNull=nullconstmyUndefined=undefined// object typesconstmyObject={}constmyArray=[]constmyFunction=function(){}constmyError=newError('error')constmyDate=newDate()constmyRegex=/a/constmyMap=newMap()constmySet=newSet()constmyPromise=Promise.resolve()constmyGenerator=function*(){}constmyClass=class{}

Go

package mainfuncmain() {// primitivesvarmyBoolbool=truevarmyIntint=10varmyInt8int8=10varmyInt16int16=10varmyInt32int32=10varmyInt64int64=10varmyUintuint=10varmyUint8uint8=10varmyUint16uint16=10varmyUint32uint32=10varmyUint64uint64=10varmyUintptruintptr=10varmyFloat32float32=10.5varmyFloat64float64=10.5varmyComplex64complex64=-1+10ivarmyComplex128complex128=-1+10ivarmyStringstring="foo"varmyBytebyte=10// alias to uint8varmyRunerune='a'// alias to int32// composite typesvarmyStructstruct{}=struct{}{}varmyArray []string= []string{}varmyMapmap[string]int=map[string]int{}varmyFunctionfunc()=func() {}varmyChannelchanbool=make(chanbool)varmyInterfaceinterface{}=nilvarmyPointer*int=new(int)}

⬆ back to top

type check


Node.js

functiontypeOf(obj){return{}.toString.call(obj).split(' ')[1].slice(0,-1).toLowerCase()}constvalues=[true,10,'foo',Symbol('bar'),null,undefined,NaN,{},[],function(){},newError(),newDate(),/a/,newMap(),newSet(),Promise.resolve(),function*(){},class{},]for(valueofvalues){console.log(typeOf(value))}

Output

booleannumberstringsymbolnullundefinednumberobjectarrayfunctionerrordateregexpmapsetpromisegeneratorfunctionfunction

Go

package mainimport ("fmt""reflect""regexp""time")funcmain() {values:= []interface{}{true,int8(10),int16(10),int32(10),int64(10),uint(10),uint8(10),uint16(10),uint32(10),uint64(10),uintptr(10),float32(10.5),float64(10.5),complex64(-1+10i),complex128(-1+10i),"foo",byte(10),'a',rune('a'),struct{}{},[]string{},map[string]int{},func() {},make(chanbool),nil,new(int),time.Now(),regexp.MustCompile(`^a$`),}for_,value:=rangevalues {fmt.Println(reflect.TypeOf(value))}}

Output

boolint8int16int32int64uintuint8uint16uint32uint64uintptrfloat32float64complex64complex128stringuint8int32int32struct {}[]stringmap[string]intfunc()chan bool<nil>*inttime.Time*regexp.Regexp

⬆ back to top

if/else


Node.js

constarray=[1,2]if(array){console.log('array exists')}if(array.length===2){console.log('length is 2')}elseif(array.length===1){console.log('length is 1')}else{console.log('length is other')}constisOddLength=array.length%2==1 ?'yes' :'no'console.log(isOddLength)

Output

array existslength is 2no

Go

package mainimport"fmt"funcmain() {array:= []byte{1,2}ifarray!=nil {fmt.Println("array exists")}iflen(array)==2 {fmt.Println("length is 2")}elseiflen(array)==1 {fmt.Println("length is 1")}else {fmt.Println("length is other")}// closest thing to ternary operatorisOddLength:="no"iflen(array)%2==1 {isOddLength="yes"}fmt.Println(isOddLength)}

Output

array existslength is 2no

⬆ back to top

for


Node.js

for(leti=0;i<=5;i++){console.log(i)}

Output

012345

Go

package mainimport"fmt"funcmain() {fori:=0;i<=5;i++ {fmt.Println(i)}}

Output

012345

⬆ back to top

while


Node.js

leti=0while(i<=5){console.log(i)i++}

Output

012345

Go

(there's nowhile keyword in Go but the same functionality is achieved by usingfor)

package mainimport"fmt"funcmain() {i:=0fori<=5 {fmt.Println(i)i++}}

Output

012345

⬆ back to top

switch


Node.js

constvalue='b'switch(value){case'a':console.log('A')breakcase'b':console.log('B')breakcase'c':console.log('C')breakdefault:console.log('first default')}switch(value){case'a':console.log('A - falling through')case'b':console.log('B - falling through')case'c':console.log('C - falling through')default:console.log('second default')}

Output

BB - falling throughC - falling throughsecond default

Go

package mainimport"fmt"funcmain() {value:="b"switchvalue {case"a":fmt.Println("A")case"b":fmt.Println("B")case"c":fmt.Println("C")default:fmt.Println("first default")}switchvalue {case"a":fmt.Println("A - falling through")fallthroughcase"b":fmt.Println("B - falling through")fallthroughcase"c":fmt.Println("C - falling through")fallthroughdefault:fmt.Println("second default")}}

Output

BB - falling throughC - falling throughsecond default

⬆ back to top

arrays


Examples of slicing, copying, appending, and prepending arrays.

Node.js

constarray=[1,2,3,4,5]console.log(array)constclone=array.slice(0)console.log(clone)constsub=array.slice(2,4)console.log(sub)constconcatenated=clone.concat([6,7])console.log(concatenated)constprepended=[-2,-1,0].concat(concatenated)console.log(prepended)

Output

[ 1, 2, 3, 4, 5 ][ 1, 2, 3, 4, 5 ][ 3, 4 ][ 1, 2, 3, 4, 5, 6, 7 ][ -2, -1, 0, 1, 2, 3, 4, 5, 6, 7 ]

Go

package mainimport"fmt"funcmain() {array:= []int{1,2,3,4,5}fmt.Println(array)clone:=make([]int,len(array))copy(clone,array)fmt.Println(clone)sub:=array[2:4]fmt.Println(sub)concatenated:=append(array, []int{6,7}...)fmt.Println(concatenated)prepended:=append([]int{-2,-1,0},concatenated...)fmt.Println(prepended)}

Output

[1 2 3 4 5][1 2 3 4 5][3 4][1 2 3 4 5 6 7][-2 -1 0 1 2 3 4 5 6 7]

⬆ back to top

uint8 arrays


Node.js

constarray=newUint8Array(10)console.log(array)constoffset=1array.set([1,2,3],offset)console.log(array)constsub=array.subarray(2)console.log(sub)constsub2=array.subarray(2,4)console.log(sub2)console.log(array)constvalue=9conststart=5constend=10array.fill(value,start,end)console.log(array)console.log(array.byteLength)

Output

Uint8Array [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]Uint8Array [ 0, 1, 2, 3, 0, 0, 0, 0, 0, 0 ]Uint8Array [ 2, 3, 0, 0, 0, 0, 0, 0 ]Uint8Array [ 2, 3 ]Uint8Array [ 0, 1, 2, 3, 0, 0, 0, 0, 0, 0 ]Uint8Array [ 0, 1, 2, 3, 0, 9, 9, 9, 9, 9 ]10

Go

package mainimport"fmt"funcmain() {array:=make([]uint8,10)fmt.Println(array)offset:=1copy(array[offset:], []uint8{1,2,3})fmt.Println(array)sub:=array[2:]fmt.Println(sub)sub2:=array[2:4]fmt.Println(sub2)fmt.Println(array)value:=uint8(9)start:=5end:=10fori:=start;i<end;i++ {array[i]=value}fmt.Println(array)fmt.Println(len(array))}

Output

[0 0 0 0 0 0 0 0 0 0][0 1 2 3 0 0 0 0 0 0][2 3 0 0 0 0 0 0][2 3][0 1 2 3 0 0 0 0 0 0][0 1 2 3 0 9 9 9 9 9]10

⬆ back to top

array iteration


Examples of iterating, mapping, filtering, and reducing arrays.

Node.js

constarray=['a','b','c']array.forEach((value,i)=>{console.log(i,value)})constmapped=array.map(value=>{returnvalue.toUpperCase()})console.log(mapped)constfiltered=array.filter((value,i)=>{returni%2==0})console.log(filtered)constreduced=array.reduce((acc,value,i)=>{if(i%2==0){acc.push(value.toUpperCase())}returnacc},[])console.log(reduced)

Output

0'a'1'b'2'c'['A','B','C' ]['a','c' ]['A','C' ]

Go

package mainimport ("fmt""strings")funcmain() {array:= []string{"a","b","c"}fori,value:=rangearray {fmt.Println(i,value)}mapped:=make([]string,len(array))fori,value:=rangearray {mapped[i]=strings.ToUpper(value)}fmt.Println(mapped)varfiltered []stringfori,value:=rangearray {ifi%2==0 {filtered=append(filtered,value)}}fmt.Println(filtered)varreduced []stringfori,value:=rangearray {ifi%2==0 {reduced=append(reduced,strings.ToUpper(value))}}fmt.Println(reduced)}

Output

0 a1 b2 c[A B C][a c][A C]

⬆ back to top

array sorting


Examples of how to sort an array

Node.js

conststringArray=['a','d','z','b','c','y']conststringArraySortedAsc=stringArray.sort((a,b)=>a>b ?1 :-1)console.log(stringArraySortedAsc)conststringArraySortedDesc=stringArray.sort((a,b)=>a>b ?-1 :1)console.log(stringArraySortedDesc)constnumberArray=[1,3,5,9,4,2,0]constnumberArraySortedAsc=numberArray.sort((a,b)=>a-b)console.log(numberArraySortedAsc)constnumberArraySortedDesc=numberArray.sort((a,b)=>b-a)console.log(numberArraySortedDesc)constcollection=[{name:"Li L",age:8},{name:"Json C",age:3},{name:"Zack W",age:15},{name:"Yi M",age:2}]constcollectionSortedByAgeAsc=collection.sort((a,b)=>a.age-b.age)console.log(collectionSortedByAgeAsc)constcollectionSortedByAgeDesc=collection.sort((a,b)=>b.age-a.age)console.log(collectionSortedByAgeDesc)

Output

['a','b','c','d','y','z' ]['z','y','d','c','b','a' ][ 0, 1, 2, 3, 4, 5, 9 ][ 9, 5, 4, 3, 2, 1, 0 ][ { name:'Yi M', age: 2 },  { name:'Json C', age: 3 },  { name:'Li L', age: 8 },  { name:'Zack W', age: 15 } ][ { name:'Zack W', age: 15 },  { name:'Li L', age: 8 },  { name:'Json C', age: 3 },  { name:'Yi M', age: 2 } ]

Go

package mainimport ("fmt""sort")typePersonstruct {NamestringAgeint}typePersonCollection []Personfunc (pcPersonCollection)Len()int {returnlen(pc)}func (pcPersonCollection)Swap(i,jint) {pc[i],pc[j]=pc[j],pc[i]}func (pcPersonCollection)Less(i,jint)bool {// ascreturnpc[i].Age<pc[j].Age}funcmain() {intList:= []int{1,3,5,9,4,2,0}// ascsort.Ints(intList)fmt.Println(intList)// descsort.Sort(sort.Reverse(sort.IntSlice(intList)))fmt.Println(intList)stringList:= []string{"a","d","z","b","c","y"}// ascsort.Strings(stringList)fmt.Println(stringList)// descsort.Sort(sort.Reverse(sort.StringSlice(stringList)))fmt.Println(stringList)collection:= []Person{{"Li L",8},{"Json C",3},{"Zack W",15},{"Yi M",2},}// ascsort.Sort(PersonCollection(collection))fmt.Println(collection)// descsort.Sort(sort.Reverse(PersonCollection(collection)))fmt.Println(collection)}

Output

[0 1 2 3 4 5 9][9 5 4 3 2 1 0][a b c d y z][z y d c b a][{Yi M 2} {Json C 3} {Li L 8} {Zack W 15}][{Zack W 15} {Li L 8} {Json C 3} {Yi M 2}]

⬆ back to top

buffers


Examples of how to allocate a buffer, write in big or little endian format, encode to a hex string, and check if buffers are equal.

Node.js

constbuf=Buffer.alloc(6)letvalue=0x1234567890abletoffset=0letbyteLength=6buf.writeUIntBE(value,offset,byteLength)lethexstr=buf.toString('hex')console.log(hexstr)constbuf2=Buffer.alloc(6)value=0x1234567890aboffset=0byteLength=6buf2.writeUIntLE(value,offset,byteLength)hexstr=buf2.toString('hex')console.log(hexstr)letisEqual=Buffer.compare(buf,buf2)===0console.log(isEqual)isEqual=Buffer.compare(buf,buf)===0console.log(isEqual)

Output

1234567890abab9078563412falsetrue

Go

package mainimport ("bytes""encoding/binary""encoding/hex""fmt""log""math/big""reflect")funcwriteUIntBE(buffer []byte,value,offset,byteLengthint64) {slice:=make([]byte,byteLength)val:=new(big.Int)val.SetUint64(uint64(value))valBytes:=val.Bytes()buf:=bytes.NewBuffer(slice)err:=binary.Write(buf,binary.BigEndian,&valBytes)iferr!=nil {log.Fatal(err)}slice=buf.Bytes()slice=slice[int64(len(slice))-byteLength :len(slice)]copy(buffer[offset:],slice)}funcwriteUIntLE(buffer []byte,value,offset,byteLengthint64) {slice:=make([]byte,byteLength)val:=new(big.Int)val.SetUint64(uint64(value))valBytes:=val.Bytes()tmp:=make([]byte,len(valBytes))fori:=rangevalBytes {tmp[i]=valBytes[len(valBytes)-1-i]}copy(slice,tmp)copy(buffer[offset:],slice)}funcmain() {buf:=make([]byte,6)writeUIntBE(buf,0x1234567890ab,0,6)fmt.Println(hex.EncodeToString(buf))buf2:=make([]byte,6)writeUIntLE(buf2,0x1234567890ab,0,6)fmt.Println(hex.EncodeToString(buf2))isEqual:=reflect.DeepEqual(buf,buf2)fmt.Println(isEqual)isEqual=reflect.DeepEqual(buf,buf)fmt.Println(isEqual)}

Output

1234567890abab9078563412falsetrue

⬆ back to top

maps


Node.js

constmap=newMap()map.set('foo','bar')letfound=map.has('foo')console.log(found)letitem=map.get('foo')console.log(item)map.delete('foo')found=map.has('foo')console.log(found)item=map.get('foo')console.log(item)constmap2={}map2['foo']='bar'item=map2['foo']deletemap2['foo']constmap3=newMap()map3.set('foo',100)map3.set('bar',200)map3.set('baz',300)for(let[key,value]ofmap3){console.log(key,value)}

Output

truebarfalseundefinedfoo 100bar 200baz 300

Go

package mainimport"fmt"funcmain() {map1:=make(map[string]string)map1["foo"]="bar"item,found:=map1["foo"]fmt.Println(found)fmt.Println(item)delete(map1,"foo")item,found=map1["foo"]fmt.Println(found)fmt.Println(item)map2:=make(map[string]int)map2["foo"]=100map2["bar"]=200map2["baz"]=300forkey,value:=rangemap2 {fmt.Println(key,value)}}

Output

truebarfalsefoo 100bar 200baz 300

⬆ back to top

objects


Node.js

constobj={someProperties:{'foo':'bar'},someMethod:(prop)=>{returnobj.someProperties[prop]}}letitem=obj.someProperties['foo']console.log(item)item=obj.someMethod('foo')console.log(item)

Output

barbar

Go

package mainimport"fmt"typeObjstruct {SomePropertiesmap[string]string}funcNewObj()*Obj {return&Obj{SomeProperties:map[string]string{"foo":"bar",},}}func (o*Obj)SomeMethod(propstring)string {returno.SomeProperties[prop]}funcmain() {obj:=NewObj()item:=obj.SomeProperties["foo"]fmt.Println(item)item=obj.SomeMethod("foo")fmt.Println(item)}

Output

barbar

⬆ back to top

functions


Node.js

functionadd(a,b){returna+b}constresult=add(2,3)console.log(result)

Output

5

Go

package mainimport"fmt"funcadd(aint,bint)int {returna+b}funcmain() {result:=add(2,3)fmt.Println(result)}

Output

5

⬆ back to top

default values


Node.js

functiongreet(name='stranger'){return`hello${name}`}letmessage=greet()console.log(message)message=greet('bob')console.log(message)

Output

hello strangerhello bob

Go

use pointers and check for nil to know if explicitly left blank

package mainimport"fmt"funcgreet(name*string)string {n:="stranger"ifname!=nil {n=*name}returnfmt.Sprintf("hello %s",n)}funcmain() {message:=greet(nil)fmt.Println(message)name:="bob"message=greet(&name)fmt.Println(message)}

Output

hello strangerhello bob

⬆ back to top

destructuring


Node.js

constobj={key:'foo',value:'bar'}const{ key, value}=objconsole.log(key,value)

Output

foo bar

Go

package mainimport"fmt"typeObjstruct {KeystringValuestring}func (o*Obj)Read() (string,string) {returno.Key,o.Value}funcmain() {obj:=Obj{Key:"foo",Value:"bar",}// option 1: multiple variable assignmentkey,value:=obj.Key,obj.Valuefmt.Println(key,value)// option 2: return multiple values from a functionkey,value=obj.Read()fmt.Println(key,value)}

Output

foo barfoo bar

⬆ back to top

spread operator


Node.js

constarray=[1,2,3,4,5]console.log(...array)

Output

1 2 3 4 5

Go

package mainimport"fmt"funcmain() {array:= []byte{1,2,3,4,5}vari []interface{}for_,value:=rangearray {i=append(i,value)}fmt.Println(i...)}

Output

1 2 3 4 5

⬆ back to top

rest operator


Node.js

functionsum(...nums){lett=0for(letnofnums){t+=n}returnt}consttotal=sum(1,2,3,4,5)console.log(total)

Output

15

Go

package mainimport"fmt"funcsum(nums...int)int {vartintfor_,n:=rangenums {t+=n}returnt}funcmain() {total:=sum(1,2,3,4,5)fmt.Println(total)}

Output

15

⬆ back to top

swapping


Node.js

leta='foo'letb='bar'console.log(a,b);[b,a]=[a,b]console.log(a,b)

Output

foo barbar foo

Go

package mainimport"fmt"funcmain() {a:="foo"b:="bar"fmt.Println(a,b)b,a=a,bfmt.Println(a,b)}

Output

foo barbar foo

⬆ back to top

classes


Examples of classes, constructors, instantiation, and "this" keyword.

Node.js

classFoo{constructor(value){this.item=value}getItem(){returnthis.item}setItem(value){this.item=value}}constfoo=newFoo('bar')console.log(foo.item)foo.setItem('qux')constitem=foo.getItem()console.log(item)

Output

barqux

Go

(closest thing to a class is to use a structure)

package mainimport"fmt"typeFoostruct {Itemstring}funcNewFoo(valuestring)*Foo {return&Foo{Item:value,}}func (f*Foo)GetItem()string {returnf.Item}func (f*Foo)SetItem(valuestring) {f.Item=value}funcmain() {foo:=NewFoo("bar")fmt.Println(foo.Item)foo.SetItem("qux")item:=foo.GetItem()fmt.Println(item)}

Output

barqux

⬆ back to top

generators


Node.js

function*generator(){yield'hello'yield'world'}letgen=generator()while(true){let{ value, done}=gen.next()console.log(value,done)if(done){break}}// alternativelyfor(letvalueofgenerator()){console.log(value)}

Output

hellofalseworldfalseundefinedtruehelloworld

Go

package mainimport"fmt"funcGenerator()chanstring {c:=make(chanstring)gofunc() {c<-"hello"c<-"world"close(c)}()returnc}funcGeneratorFunc()func() (string,bool) {s:= []string{"hello","world"}i:=-1returnfunc() (string,bool) {i++ifi>=len(s) {return"",false}returns[i],true}}funcmain() {gen:=Generator()for {value,more:=<-genfmt.Println(value,more)if!more {break}}// alternativelyforvalue:=rangeGenerator() {fmt.Println(value)}// alternativelygenfn:=GeneratorFunc()for {value,more:=genfn()fmt.Println(value,more)if!more {break}}}

Output

hellotrueworldtruefalsehelloworldhellotrueworldtruefalse

⬆ back to top

datetime


Examples of parsing, formatting, and getting unix timestamp of dates.

Node.js

constnowUnix=Date.now()console.log(nowUnix)constdatestr='2019-01-17T09:24:23+00:00'constdate=newDate(datestr)console.log(date.getTime())console.log(date.toString())constfutureDate=newDate(date)futureDate.setDate(date.getDate()+14)console.log(futureDate.toString())constformatted=`${String(date.getMonth()+1).padStart(2,0)}/${String(date.getDate()).padStart(2,0)}/${date.getFullYear()}`console.log(formatted)

Output

15477188441681547717063000Thu Jan 17 2019 01:24:23 GMT-0800 (Pacific Standard Time)Thu Jan 31 2019 01:24:23 GMT-0800 (Pacific Standard Time)01/17/2019

Go

package mainimport ("fmt""time")funcmain() {nowUnix:=time.Now().Unix()fmt.Println(nowUnix)datestr:="2019-01-17T09:24:23+00:00"date,err:=time.Parse("2006-01-02T15:04:05Z07:00",datestr)iferr!=nil {panic(err)}fmt.Println(date.Unix())fmt.Println(date.String())futureDate:=date.AddDate(0,0,14)fmt.Println(futureDate.String())formatted:=date.Format("01/02/2006")fmt.Println(formatted)}

Output

154771884415477170632019-01-17 09:24:23 +0000 +00002019-01-31 09:24:23 +0000 +000001/17/2019

⬆ back to top

timeout


Node.js

setTimeout(callback,1e3)functioncallback(){console.log('called')}

Output

called

Go

package mainimport ("fmt""sync""time")varwg sync.WaitGroupfunccallback() {deferwg.Done()fmt.Println("called")}funcmain() {wg.Add(1)time.AfterFunc(1*time.Second,callback)wg.Wait()}

Output

called

⬆ back to top

interval


Node.js

leti=0constid=setInterval(callback,1e3)functioncallback(){console.log('called',i)if(i===3){clearInterval(id)}i++}

Output

called 0called 1called 2called 3

Go

package mainimport ("fmt""time")funccallback(iint) {fmt.Println("called",i)}funcmain() {ticker:=time.NewTicker(1*time.Second)i:=0forrangeticker.C {callback(i)ifi==3 {ticker.Stop()break}i++}}

Output

called 0called 1called 2called 3

⬆ back to top

IIFE


Immediately invoked function expression

Node.js

(function(name){console.log('hello',name)})('bob')

Output

hello bob

Go

package mainimport"fmt"funcmain() {func(namestring) {fmt.Println("hello",name)}("bob")}

Output

hello bob

⬆ back to top

files


Examples of creating, opening, writing, reading, closing, and deleting files.

Node.js

constfs=require('fs')// create filefs.closeSync(fs.openSync('test.txt','w'))// open file (returns file descriptor)constfd=fs.openSync('test.txt','r+')letwbuf=Buffer.from('hello world.')letrbuf=Buffer.alloc(12)letoff=0letlen=12letpos=0// write filefs.writeSync(fd,wbuf,pos)// read filefs.readSync(fd,rbuf,off,len,pos)console.log(rbuf.toString())// close filefs.closeSync(fd)// delete filefs.unlinkSync('test.txt')

Output

hello world.

Go

package mainimport ("fmt""os""syscall")funcmain() {// create filefile,err:=os.Create("test.txt")iferr!=nil {panic(err)}// close filefile.Close()// open filefile,err=os.OpenFile("test.txt",os.O_RDWR,0755)iferr!=nil {panic(err)}// file descriptorfd:=file.Fd()// open file (using file descriptor)file=os.NewFile(fd,"test file")wbuf:= []byte("hello world.")rbuf:=make([]byte,12)varoffint64// write fileif_,err:=file.WriteAt(wbuf,off);err!=nil {panic(err)}// read fileif_,err:=file.ReadAt(rbuf,off);err!=nil {panic(err)}fmt.Println(string(rbuf))// close file (using file descriptor)iferr:=syscall.Close(int(fd));err!=nil {panic(err)}// delete fileiferr:=os.Remove("test.txt");err!=nil {panic(err)}}

Output

hello world.

⬆ back to top

json


Examples of how to parse (unmarshal) and stringify (marshal) JSON.

Node.js

letjsonstr='{"foo":"bar"}'letparsed=JSON.parse(jsonstr)console.log(parsed)jsonstr=JSON.stringify(parsed)console.log(jsonstr)

Output

{ foo:'bar' }{"foo":"bar"}

Go

package mainimport ("encoding/json""fmt")typeTstruct {Foostring`json:"foo"`}funcmain() {jsonstr:=`{"foo":"bar"}`t:=new(T)err:=json.Unmarshal([]byte(jsonstr),t)iferr!=nil {panic(err)}fmt.Println(t)marshalled,err:=json.Marshal(t)jsonstr=string(marshalled)fmt.Println(jsonstr)}

Output

&{bar}{"foo":"bar"}

⬆ back to top

big numbers


Examples of creating big number types from and to uint, string, hex, and buffers.

Node.js

letbn=75n;console.log(bn.toString(10))bn=BigInt('75')console.log(bn.toString(10))bn=BigInt(0x4b)console.log(bn.toString(10))bn=BigInt('0x4b')console.log(bn.toString(10))bn=BigInt('0x'+Buffer.from('4b','hex').toString('hex'))console.log(bn.toString(10))console.log(Number(bn))console.log(bn.toString(16))console.log(Buffer.from(bn.toString(16),'hex'))letbn2=BigInt(100)letisEqual=bn===bn2console.log(isEqual)letisGreater=bn>bn2console.log(isGreater)letisLesser=bn<bn2console.log(isLesser)

Output

7575757575754b<Buffer 4b>falsefalsetrue

Go

package mainimport ("encoding/hex""fmt""math/big")funcmain() {bn:=new(big.Int)bn.SetUint64(75)fmt.Println(bn.String())bn=new(big.Int)bn.SetString("75",10)fmt.Println(bn.String())bn=new(big.Int)bn.SetUint64(0x4b)fmt.Println(bn.String())bn=new(big.Int)bn.SetString("4b",16)fmt.Println(bn.String())bn=new(big.Int)bn.SetBytes([]byte{0x4b})fmt.Println(bn.String())fmt.Println(bn.Uint64())fmt.Println(hex.EncodeToString(bn.Bytes()))fmt.Println(bn.Bytes())bn2:=big.NewInt(100)isEqual:=bn.Cmp(bn2)==0fmt.Println(isEqual)isGreater:=bn.Cmp(bn2)==1fmt.Println(isGreater)isLesser:=bn.Cmp(bn2)==-1fmt.Println(isLesser)}

Output

7575757575754b[75]falsefalsetrue

⬆ back to top

promises


Node.js

functionasyncMethod(value){returnnewPromise((resolve,reject)=>{setTimeout(()=>{resolve('resolved: '+value)},1e3)})}functionmain(){asyncMethod('foo').then(result=>console.log(result)).catch(err=>console.error(err))Promise.all([asyncMethod('A'),asyncMethod('B'),asyncMethod('C')]).then(result=>console.log(result)).catch(err=>console.error(err))}main()

Output

resolved: foo['resolved: A','resolved: B','resolved: C' ]

Go

(closest thing is to use channels)

package mainimport ("fmt""sync""time""github.com/prometheus/common/log")funcasyncMethod(valuestring)chaninterface{} {ch:=make(chaninterface{},1)gofunc() {time.Sleep(1*time.Second)ch<-"resolved: "+valueclose(ch)}()returnch}funcresolveAll(ch...chaninterface{})chaninterface{} {varwg sync.WaitGroupres:=make([]string,len(ch))resCh:=make(chaninterface{},1)gofunc() {fori,c:=rangech {wg.Add(1)gofunc(jint,ifcChchaninterface{}) {ifc:=<-ifcChswitchv:=ifc.(type) {caseerror:resCh<-vcasestring:res[j]=v}wg.Done()}(i,c)}wg.Wait()resCh<-resclose(resCh)}()returnresCh}funcmain() {varwg sync.WaitGroupwg.Add(2)gofunc() {result:=<-asyncMethod("foo")switchv:=result.(type) {casestring:fmt.Println(v)caseerror:log.Errorln(v)}wg.Done()}()gofunc() {result:=<-resolveAll(asyncMethod("A"),asyncMethod("B"),asyncMethod("C"),)switchv:=result.(type) {case []string:fmt.Println(v)caseerror:log.Errorln(v)}wg.Done()}()wg.Wait()}

Output

resolved: foo[resolved: A resolved: B resolved: C]

⬆ back to top

async/await


Node.js

functionhello(name){returnnewPromise((resolve,reject)=>{setTimeout(()=>{if(name==='fail'){reject(newError('failed'))}else{resolve('hello '+name)}},1e3)})}asyncfunctionmain(){try{letoutput=awaithello('bob')console.log(output)output=awaithello('fail')console.log(output)}catch(err){console.log(err.message)}}main()

Output

hello bobfailed

Go

(closest thing is to use channels)

package mainimport ("errors""fmt""time""github.com/prometheus/common/log")funchello(namestring)chaninterface{} {ch:=make(chaninterface{},1)gofunc() {time.Sleep(1*time.Second)ifname=="fail" {ch<-errors.New("failed")}else {ch<-"hello "+name}}()returnch}funcmain() {result:=<-hello("bob")switchv:=result.(type) {casestring:fmt.Println(v)caseerror:log.Errorln(v)}result=<-hello("fail")switchv:=result.(type) {casestring:fmt.Println(v)caseerror:log.Errorln(v)}}

Output

hello bobfailed

⬆ back to top

streams


Examples of reading and writing streams

Node.js

const{ Readable, Writable}=require('stream')constinStream=newReadable()inStream.push(Buffer.from('foo'))inStream.push(Buffer.from('bar'))inStream.push(null)// end streaminStream.pipe(process.stdout)constoutStream=newWritable({write(chunk,encoding,callback){console.log('received: '+chunk.toString('utf8'))callback()}})outStream.write(Buffer.from('abc'))outStream.write(Buffer.from('xyz'))outStream.end()

Output

foobarreceived: abcreceived: xyz

Go

package mainimport ("bufio""bytes""fmt""io""os""runtime")funcmain() {inStream:=new(bytes.Buffer)w:=bufio.NewWriter(inStream)_,err:=w.Write([]byte("foo"))iferr!=nil {panic(err)}_,err=w.Write([]byte("bar"))iferr!=nil {panic(err)}err=w.Flush()iferr!=nil {panic(err)}inStream.WriteTo(os.Stdout)fmt.Print("\n")outStream:=new(bytes.Buffer)outStream.Write([]byte("abc\n"))outStream.Write([]byte("xyc\n"))piper,pipew:=io.Pipe()gofunc() {sc:=bufio.NewScanner(piper)forsc.Scan() {fmt.Println("received: "+sc.Text())}iferr:=sc.Err();err!=nil {panic(err)}os.Exit(0)}()gofunc() {deferpipew.Close()io.Copy(pipew,outStream)}()deferruntime.Goexit()}

Output

foobarreceived: abcreceived: xyc

⬆ back to top

event emitter


Node.js

constEventEmitter=require('events')classMyEmitterextendsEventEmitter{}constmyEmitter=newMyEmitter()myEmitter.on('my-event',msg=>{console.log(msg)})myEmitter.on('my-other-event',msg=>{console.log(msg)})myEmitter.emit('my-event','hello world')myEmitter.emit('my-other-event','hello other world')

Output

hello worldhello other world

Go

(closest thing is to use channels)

package mainimport ("fmt")typeMyEmittermap[string]chanstringfuncmain() {myEmitter:=MyEmitter{}myEmitter["my-event"]=make(chanstring)myEmitter["my-other-event"]=make(chanstring)gofunc() {for {select {casemsg:=<-myEmitter["my-event"]:fmt.Println(msg)casemsg:=<-myEmitter["my-other-event"]:fmt.Println(msg)}}}()myEmitter["my-event"]<-"hello world"myEmitter["my-other-event"]<-"hello other world"}

Output

hello worldhello other world

⬆ back to top

errors


Node.js

consterr1=newError('some error')console.log(err1)classFooErrorextendsError{constructor(message){super(message)this.name='FooError'this.message=message}toString(){returnthis.message}}consterr2=newFooError('my custom error')console.log(err2)

Output

Error: some error{ FooError: my custom error }

Go

package mainimport ("errors""fmt")typeFooErrorstruct {sstring}func (f*FooError)Error()string {returnf.s}funcNewFooError(sstring)error {return&FooError{s}}funcmain() {err1:=errors.New("some error")fmt.Println(err1)err2:=NewFooError("my custom error")fmt.Println(err2)}

Output

some errormy custom error

⬆ back to top

try/catch


Node.js

functionfoo(fail){if(fail){throwError('my error')}}functionmain(){try{foo(true)}catch(err){console.log(`caught error:${err.message}`)}}main()

Output

caught error: my error

Go

package mainimport ("errors""fmt")funcfoo(failbool)error {iffail {returnerrors.New("my error")}returnnil}funcmain() {err:=foo(true)iferr!=nil {fmt.Printf("caught error: %s\n",err.Error())}}

Output

caught error: my error

⬆ back to top

exceptions


Node.js

functionfoo(){throwError('my exception')}functionmain(){foo()}process.on('uncaughtException',err=>{console.log(`caught exception:${err.message}`)process.exit(1)})main()

Output

caught exception: my exception

Go

package mainimport ("fmt")funcfoo() {panic("my exception")}funcmain() {deferfunc() {ifr:=recover();r!=nil {fmt.Printf("caught exception: %s",r)}}()foo()}

Output

caught exception: my exception

⬆ back to top

regex


Node.js

letinput='foobar'letreplaced=input.replace(/foo(.*)/i,'qux$1')console.log(replaced)letmatch=/o{2}/i.test(input)console.log(match)input='111-222-333'letmatches=input.match(/([0-9]+)/gi)console.log(matches)

Output

quxbartrue['111','222','333' ]

Go

package mainimport ("fmt""regexp")funcmain() {input:="foobar"re:=regexp.MustCompile(`(?i)foo(.*)`)replaced:=re.ReplaceAllString(input,"qux$1")fmt.Println(replaced)re=regexp.MustCompile(`(?i)o{2}`)match:=re.Match([]byte(input))fmt.Println(match)input="111-222-333"re=regexp.MustCompile(`(?i)([0-9]+)`)matches:=re.FindAllString(input,-1)fmt.Println(matches)}

Output

quxbartrue[111 222 333]

⬆ back to top

exec (sync)


Node.js

const{ execSync}=require('child_process')constoutput=execSync(`echo 'hello world'`)console.log(output.toString())

Output

hello world

Go

package mainimport ("fmt""os/exec")funcmain() {output,err:=exec.Command("echo","hello world").Output()iferr!=nil {panic(err)}fmt.Println(string(output))}

Output

hello world

⬆ back to top

exec (async)


Node.js

const{ exec}=require('child_process')exec(`echo 'hello world'`,(error,stdout,stderr)=>{if(error){console.error(err)}if(stderr){console.error(stderr)}if(stdout){console.log(stdout)}})

Output

hello world

Go

package mainimport ("os""os/exec")funcmain() {cmd:=exec.Command("echo","hello world")cmd.Stdout=os.Stdoutcmd.Stderr=os.Stderrcmd.Run()}

Output

hello world

⬆ back to top

tcp server


Node.js

constnet=require('net')functionhandler(socket){socket.write('Received: ')socket.pipe(socket)}constserver=net.createServer(handler)server.listen(3000)

Output

$echo'hello'| nc localhost 3000Received: hello

Go

package mainimport ("bufio""net")funchandler(conn net.Conn) {deferconn.Close()reader:=bufio.NewReader(conn)for {message,err:=reader.ReadString('\n')iferr!=nil {return}conn.Write([]byte("Received: "))conn.Write([]byte(message))}}funcmain() {listener,err:=net.Listen("tcp",":3000")iferr!=nil {panic(err)}deferlistener.Close()for {conn,err:=listener.Accept()iferr!=nil {panic(err)}gohandler(conn)}}

Output

$echo'hello'| nc localhost 3000Received: hello

⬆ back to top

udp server


Node.js

constdgram=require('dgram')constserver=dgram.createSocket('udp4')server.on('error',err=>{console.error(err)server.close()})server.on('message',(msg,rinfo)=>{constdata=msg.toString('utf8').trim()console.log(`received:${data} from${rinfo.address}:${rinfo.port}`)})server.on('listening',()=>{constaddress=server.address()console.log(`server listening${address.address}:${address.port}`)})server.bind(3000)

Output

$echo'hello world'> /dev/udp/0.0.0.0/3000server listening 0.0.0.0:3000received: hello world from 127.0.0.1:51452

Go

package mainimport ("fmt""net""strings")funcmain() {conn,err:=net.ListenUDP("udp",&net.UDPAddr{Port:3000,IP:net.ParseIP("0.0.0.0"),})iferr!=nil {panic(err)}deferconn.Close()fmt.Printf("server listening %s\n",conn.LocalAddr().String())for {message:=make([]byte,20)rlen,remote,err:=conn.ReadFromUDP(message[:])iferr!=nil {panic(err)}data:=strings.TrimSpace(string(message[:rlen]))fmt.Printf("received: %s from %s\n",data,remote)}}

Output

$echo'hello world'> /dev/udp/0.0.0.0/3000server listening [::]:3000received: hello world from 127.0.0.1:50275

⬆ back to top

http server


Node.js

consthttp=require('http')functionhandler(request,response){response.writeHead(200,{'Content-type':'text/plain'})response.write('hello world')response.end()}constserver=http.createServer(handler)server.listen(8080)

Output

$ curl http://localhost:8080hello world

Go

package mainimport ("net/http")funchandler(w http.ResponseWriter,r*http.Request) {w.WriteHeader(200)w.Write([]byte("hello world"))}funcmain() {http.HandleFunc("/",handler)iferr:=http.ListenAndServe(":8080",nil);err!=nil {panic(err)}}

Output

$ curl http://localhost:8080hello world

⬆ back to top

url parse


Node.js

consturl=require('url')constqs=require('querystring')consturlstr='http://bob:secret@sub.example.com:8080/somepath?foo=bar'constparsed=url.parse(urlstr)console.log(parsed.protocol)console.log(parsed.auth)console.log(parsed.port)console.log(parsed.hostname)console.log(parsed.pathname)console.log(qs.parse(parsed.search.substr(1)))

Output

http:bob:secret8080sub.example.com/somepath{ foo:'bar' }

Go

package mainimport ("fmt""net/url")funcmain() {urlstr:="http://bob:secret@sub.example.com:8080/somepath?foo=bar"u,err:=url.Parse(urlstr)iferr!=nil {panic(err)}fmt.Println(u.Scheme)fmt.Println(u.User)fmt.Println(u.Port())fmt.Println(u.Hostname())fmt.Println(u.Path)fmt.Println(u.Query())}

Output

httpbob:secret8080sub.example.com/somepathmap[foo:[bar]]

⬆ back to top

gzip


Node.js

constzlib=require('zlib')constdata=Buffer.from('hello world','utf-8')zlib.gzip(data,(err,compressed)=>{if(err){console.error(err)}console.log(compressed)zlib.unzip(compressed,(err,decompressed)=>{if(err){console.error(err)}console.log(decompressed.toString())})})

Output

<Buffer 1f 8b 08 00 00 00 00 00 00 13 cb 48cd c9 c9 57 28 cf 2f ca 49 01 00 85 11 4a 0d 0b 00 0000>hello world

Go

package mainimport ("bytes""compress/gzip""fmt")funcmain() {data:= []byte("hello world")compressed:=new(bytes.Buffer)w:=gzip.NewWriter(compressed)if_,err:=w.Write(data);err!=nil {panic(err)}iferr:=w.Close();err!=nil {panic(err)}fmt.Println(compressed.Bytes())decompressed:=new(bytes.Buffer)r,err:=gzip.NewReader(compressed)iferr!=nil {panic(err)}_,err=decompressed.ReadFrom(r)iferr!=nil {panic(err)}fmt.Println(string(decompressed.Bytes()))}

Output

[31 139 8 0 0 0 0 0 0 255 202 72 205 201 201 87 40 207 47 202 73 1 4 0 0 255 255 133 17 74 13 11 0 0 0]hello world

⬆ back to top

dns


DNS lookup examples

Node.js

constdns=require('dns')dns.resolveNs('google.com',(err,ns)=>{if(err){console.error(err)}console.log(ns)})dns.resolve4('google.com',(err,ips)=>{if(err){console.error(err)}console.log(ips)})dns.resolveMx('google.com',(err,mx)=>{if(err){console.error(err)}console.log(mx)})dns.resolveTxt('google.com',(err,txt)=>{if(err){console.error(err)}console.log(txt)})dns.setServers(['1.1.1.1'])console.log(dns.getServers())dns.resolveNs('google.com',(err,ns)=>{if(err){console.error(err)}console.log(ns)})

Output

['ns2.google.com','ns3.google.com','ns4.google.com','ns1.google.com']['172.217.11.78' ][ { exchange:'alt4.aspmx.l.google.com', priority: 50 },  { exchange:'alt2.aspmx.l.google.com', priority: 30 },  { exchange:'alt3.aspmx.l.google.com', priority: 40 },  { exchange:'aspmx.l.google.com', priority: 10 },  { exchange:'alt1.aspmx.l.google.com', priority: 20 } ][ ['v=spf1 include:_spf.google.com ~all' ],  ['docusign=05958488-4752-4ef2-95eb-aa7ba8a3bd0e' ],  ['facebook-domain-verification=22rm551cu4k0ab0bxsw536tlds4h95' ],  ['globalsign-smime-dv=CDYX+XFHUw2wml6/Gb8+59BsH31KzUr6c1l2BPvqKX8=' ] ]['1.1.1.1' ]['ns1.google.com','ns2.google.com','ns4.google.com','ns3.google.com']

Go

package mainimport ("fmt""net")funcmain() {ns,err:=net.LookupNS("google.com")iferr!=nil {panic(err)}fmt.Printf("%s\n",ns)ips,err:=net.LookupIP("google.com")iferr!=nil {panic(err)}fmt.Println(ips)mx,err:=net.LookupMX("google.com")iferr!=nil {panic(err)}fmt.Println(mx)txt,err:=net.LookupTXT("google.com")iferr!=nil {panic(err)}fmt.Println(txt)r:=&net.Resolver{PreferGo:true,Dial:func(ctx context.Context,network,addressstring) (net.Conn,error) {d:= net.Dialer{Timeout:time.Millisecond*time.Duration(10_000),}returnd.DialContext(ctx,"udp","1.1.1.1:53")},}ns,_=r.LookupNS(context.Background(),"google.com")fmt.Printf("%s",ns)}

Output

[%!s(*net.NS=&{ns3.google.com.}) %!s(*net.NS=&{ns4.google.com.}) %!s(*net.NS=&{ns1.google.com.}) %!s(*net.NS=&{ns2.google.com.})][172.217.5.78 2607:f8b0:4007:80d::200e][0xc0000ba2e0 0xc0000ba260 0xc0000ba2a0 0xc0000ba280 0xc0000ba300][facebook-domain-verification=22rm551cu4k0ab0bxsw536tlds4h95 docusign=05958488-4752-4ef2-95eb-aa7ba8a3bd0e v=spf1 include:_spf.google.com~all globalsign-smime-dv=CDYX+XFHUw2wml6/Gb8+59BsH31KzUr6c1l2BPvqKX8=][%!s(*net.NS=&{ns2.google.com.}) %!s(*net.NS=&{ns1.google.com.}) %!s(*net.NS=&{ns3.google.com.}) %!s(*net.NS=&{ns4.google.com.})]

⬆ back to top

crypto


Node.js

constcrypto=require('crypto')consthash=crypto.createHash('sha256').update(Buffer.from('hello')).digest()console.log(hash.toString('hex'))

Output

2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

Go

package mainimport ("crypto/sha256""encoding/hex""fmt")funcmain() {hash:=sha256.Sum256([]byte("hello"))fmt.Println(hex.EncodeToString(hash[:]))}

Output

2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

⬆ back to top

env vars


Node.js

constkey=process.env['API_KEY']console.log(key)

Output

$ API_KEY=foobar node examples/env_vars.jsfoobar

Go

package mainimport ("fmt""os")funcmain() {key:=os.Getenv("API_KEY")fmt.Println(key)}

Output

$ API_KEY=foobar go run examples/env_vars.gofoobar

⬆ back to top

cli args


Node.js

constargs=process.argv.slice(2)console.log(args)

Output

$ node examples/cli_args.js foo bar qux['foo','bar','qux' ]

Go

package mainimport ("fmt""os")funcmain() {args:=os.Args[1:]fmt.Println(args)}

Output

$ go run examples/cli_args.go foo bar qux[foo bar qux]

⬆ back to top

cli flags


Node.js

constyargs=require('yargs')const{ foo='default value', qux=false}=yargs.argvconsole.log('foo:',foo)console.log('qux:',qux)

Output

$ node examples/cli_flags.js --foo='bar' --qux=truefoo: barqux:true

Go

package mainimport ("flag""fmt")funcmain() {varfoostringflag.StringVar(&foo,"foo","default value","a string var")varquxboolflag.BoolVar(&qux,"qux",false,"a bool var")flag.Parse()fmt.Println("foo:",foo)fmt.Println("qux:",qux)}

Output

$ go run examples/cli_flags.go -foo='bar' -qux=truefoo: barqux:true

⬆ back to top

stdout


Node.js

process.stdout.write('hello world\n')

Output

hello world

Go

package mainimport ("fmt""os")funcmain() {fmt.Fprint(os.Stdout,"hello world\n")}

Output

hello world

⬆ back to top

stderr


Node.js

process.stderr.write('hello error\n')

Output

hello error

Go

package mainimport ("fmt""os")funcmain() {fmt.Fprint(os.Stderr,"hello error\n")}

Output

hello error

⬆ back to top

stdin


Node.js

conststdin=process.openStdin()process.stdout.write('Enter name: ')stdin.addListener('data',text=>{constname=text.toString().trim()console.log('Your name is: '+name)stdin.pause()})

Output

Enter name: bobYour name is: bob

Go

package mainimport ("bufio""fmt""os""strings")funcmain() {reader:=bufio.NewReader(os.Stdin)fmt.Print("Enter name: ")text,err:=reader.ReadString('\n')iferr!=nil {panic(err)}name:=strings.TrimSpace(text)fmt.Printf("Your name is: %s\n",name)}

Output

Enter name: bobYour name is: bob

⬆ back to top

modules


Node.js

# initializing metadata and dependencies file (package.json)$ npm init# installing a module$ npm install moment --save# updating a module$ npm install moment@latest --save# removing a module$ npm uninstall moment --save# pruning modules (removing unused modules)$ npm prune# publishing a module$ npm publish
// importing a moduleconstmoment=require('moment')constnow=moment().unix()console.log(now)

Output

1546595748
// exporting a modulemodule.exports={greet(name){console.log(`hello${name}`)}}
// importing exported moduleconstgreeter=require('./greeter')greeter.greet('bob')

Output

hello bob

Go

Setup

# enable Go modules supportGO111MODULE=on# initializing dependencies file (go.mod)$ go mod init# installing a module$ go get github.com/go-shadow/moment# updating a module$ go get -u github.com/go-shadow/moment# removing a module$ rm -rf$GOPATH/pkg/mod/github.com/go-shadow/moment@v<tag>-<checksum>/# pruning modules (removing unused modules from dependencies file)$ go mod tidy# download modules being used to local vendor directory (equivalent of downloading node_modules locally)$ go mod vendor# publishing a module:# Note: Go doesn't have an index of repositories like NPM.# Go modules are hosted as public git repositories.# To publish, simply push to the repository and tag releases.
package mainimport ("fmt"// importing a module"github.com/go-shadow/moment")funcmain() {now:=moment.New().Now().Unix()fmt.Println(now)}

Output

1546595748
package greeterimport ("fmt")// exporting a module (use a capitalized name to export function)funcGreet(namestring) {fmt.Printf("hello %s",name)}
package mainimport (// importing exported modulegreeter"github.com/miguelmota/golang-for-nodejs-developers/examples/greeter_go")funcmain() {greeter.Greet("bob")}

Output

hello bob

⬆ back to top

stack trace


Node.js

functionfoo(){thrownewError('failed')}try{foo()}catch(err){console.trace(err)}

Output

Trace: Error: failed    at foo (/Users/bob/examples/stack_trace.js:2:9)    at Object.<anonymous> (/Users/bob/examples/stack_trace.js:6:3)    at Module._compile (internal/modules/cjs/loader.js:688:30)    at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)    at Module.load (internal/modules/cjs/loader.js:598:32)    at tryModuleLoad (internal/modules/cjs/loader.js:537:12)    at Function.Module._load (internal/modules/cjs/loader.js:529:3)    at Function.Module.runMain (internal/modules/cjs/loader.js:741:12)    at startup (internal/bootstrap/node.js:285:19)    at bootstrapNodeJSCore (internal/bootstrap/node.js:739:3)    at Object.<anonymous> (/Users/bob/examples/stack_trace.js:8:11)    at Module._compile (internal/modules/cjs/loader.js:688:30)    at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)    at Module.load (internal/modules/cjs/loader.js:598:32)    at tryModuleLoad (internal/modules/cjs/loader.js:537:12)    at Function.Module._load (internal/modules/cjs/loader.js:529:3)    at Function.Module.runMain (internal/modules/cjs/loader.js:741:12)    at startup (internal/bootstrap/node.js:285:19)    at bootstrapNodeJSCore (internal/bootstrap/node.js:739:3)

Go

package mainimport ("errors""fmt""runtime/debug")funcfoo() {panic(errors.New("failed"))}funcmain() {deferfunc() {ifr:=recover();r!=nil {fmt.Println(string(debug.Stack()))}}()foo()}

Output

goroutine 1 [running]:runtime/debug.Stack(0xc000090eb8, 0x10a8400, 0xc00007e1c0)        /Users/mota/.gvm/gos/go1.11/src/runtime/debug/stack.go:24 +0xa7main.main.func1()        /Users/bob/examples/stack_trace.go:16 +0x46panic(0x10a8400, 0xc00007e1c0)        /Users/mota/.gvm/gos/go1.11/src/runtime/panic.go:513 +0x1b9main.foo(...)        /Users/bob/examples/stack_trace.go:10main.main()        /Users/bob/examples/stack_trace.go:20 +0xa2

⬆ back to top

databases


Example of creating a table, inserting rows, and reading rows from a sqlite3 database

Node.js

constsqlite3=require('sqlite3').verbose()constdb=newsqlite3.Database('./sqlite3.db')db.serialize(()=>{db.run('CREATE TABLE persons (name TEXT)')conststmt=db.prepare('INSERT INTO persons VALUES (?)')constnames=['alice','bob','charlie']for(leti=0;i<names.length;i++){stmt.run(names[i])}stmt.finalize()db.each('SELECT rowid AS id, name FROM persons',(err,row)=>{if(err){console.error(err)return}console.log(row.id,row.name)})})db.close()

Output

1'alice'2'bob'3'charlie'

Go

package mainimport ("database/sql""fmt"_"github.com/mattn/go-sqlite3")funcmain() {db,err:=sql.Open("sqlite3","./sqlite3.db")iferr!=nil {panic(err)}deferdb.Close()_,err=db.Exec("CREATE TABLE persons (name TEXT)")iferr!=nil {panic(err)}tx,err:=db.Begin()iferr!=nil {panic(err)}stmt,err:=tx.Prepare("INSERT INTO persons VALUES (?)")iferr!=nil {panic(err)}deferstmt.Close()names:= []string{"alice","bob","charlie"}for_,name:=rangenames {_,err:=stmt.Exec(name)iferr!=nil {panic(err)}}tx.Commit()rows,err:=db.Query("SELECT rowid AS id, name FROM persons")iferr!=nil {panic(err)}deferrows.Close()forrows.Next() {varidintvarnamestringerr=rows.Scan(&id,&name)iferr!=nil {panic(err)}fmt.Println(id,name)}err=rows.Err()iferr!=nil {panic(err)}}

Output

1 alice2 bob3 charlie

⬆ back to top

testing


Node.js

consttest=require('tape')test(t=>{consttt=[{a:1,b:1,ret:2},{a:2,b:3,ret:5},{a:5,b:5,ret:10}]t.plan(tt.length)tt.forEach(tt=>{t.equal(sum(tt.a,tt.b),tt.ret)})})functionsum(a,b){returna+b}

Output

$ node examples/example_test.jsTAP version 13# (anonymous)ok 1 should be equalok 2 should be equalok 3 should be equal1..3# tests 3# pass  3# ok

Go

package exampleimport ("fmt""testing")funcTestSum(t*testing.T) {for_,tt:=range []struct {aintbintretint}{{1,1,2},{2,3,5},{5,5,10},} {t.Run(fmt.Sprintf("(%v + %v)",tt.a,tt.b),func(t*testing.T) {ret:=sum(tt.a,tt.b)ifret!=tt.ret {t.Errorf("want %v, got %v",tt.ret,ret)}})}}funcsum(a,bint)int {returna+b}

Output

$ gotest -v examples/example_test.go=== RUN   TestSum=== RUN   TestSum/(1_+_1)=== RUN   TestSum/(2_+_3)=== RUN   TestSum/(5_+_5)--- PASS: TestSum (0.00s)    --- PASS: TestSum/(1_+_1) (0.00s)    --- PASS: TestSum/(2_+_3) (0.00s)    --- PASS: TestSum/(5_+_5) (0.00s)PASSok      command-line-arguments  0.008s

⬆ back to top

benchmarking


Node.js

constBenchmark=require('benchmark')constsuite=newBenchmark.Suitesuite.add('fib#recursion',()=>{fibRec(10)}).add('fib#loop',()=>{fibLoop(10)}).on('complete',()=>{console.log(suite[0].toString())console.log(suite[1].toString())}).run({async:true})functionfibRec(n){if(n<=1){returnn}returnfibRec(n-1)+fibRec(n-2)}functionfibLoop(n){letf=[0,1]for(leti=2;i<=n;i++){f[i]=f[i-1]+f[i-2]}returnf[n]}

Output

$ node examples/benchmark_test.jsfib#recursion x 1,343,074 ops/sec ±1.26% (84 runs sampled)fib#loop x 20,104,517 ops/sec ±3.78% (78 runs sampled)

Go

package exampleimport ("testing")funcBenchmarkFibRec(b*testing.B) {forn:=0;n<b.N;n++ {fibRec(10)}}funcBenchmarkFibLoop(b*testing.B) {forn:=0;n<b.N;n++ {fibLoop(10)}}funcfibRec(nint)int {ifn<=1 {returnn}returnfibRec(n-1)+fibRec(n-2)}funcfibLoop(nint)int {f:=make([]int,n+1,n+2)ifn<2 {f=f[0:2]}f[0]=0f[1]=1fori:=2;i<=n;i++ {f[i]=f[i-1]+f[i-2]}returnf[n]}

Output

$ gotest -v -bench=. -benchmem examples/benchmark_test.gogoos: darwingoarch: amd64BenchmarkFibRec-8        5000000               340 ns/op               0 B/op          0 allocs/opBenchmarkFibLoop-8      30000000                46.5 ns/op            96 B/op          1 allocs/opPASSok      command-line-arguments  3.502s

⬆ back to top

documentation


Node.js

jsdoc

/** * Creates a new Person. *@class *@example * const person = new Person('bob') */classPerson{/**   * Create a person.   *@param {string} [name] - The person's name.   */constructor(name){this.name=name}/**   * Get the person's name.   *@return {string} The person's name   *@example   * person.getName()   */getName(){returnthis.name}/**   * Set the person's name.   *@param {string} name - The person's name.   *@example   * person.setName('bob')   */setName(name){this.name=name}}

Go

godoc

person.go

package personimport"fmt"// Person is the structure of a persontypePersonstruct {namestring}// NewPerson creates a new person. Takes in a name argument.funcNewPerson(namestring)*Person {return&Person{name:name,}}// GetName returns the person's namefunc (p*Person)GetName()string {returnp.name}// SetName sets the person's namefunc (p*Person)SetName(namestring)string {returnp.name}

person_test.go

// Example of creating a new Person.funcExampleNewPerson() {person:=NewPerson("bob")_=person}// Example of getting person's name.funcExamplePerson_GetName() {person:=NewPerson("bob")fmt.Println(person.GetName())// Output: bob}// Example of setting person's name.funcExamplePerson_SetName() {person:=NewPerson("alice")person.SetName("bob")}

⬆ back to top

Contributing

Pull requests are welcome!

Please submit a pull request for new interesting additions or for general content fixes.

If updating code, update both the README and the code in theexamples folder.

License

Released under theMIT license.

©Miguel Mota

Releases

No releases published

Sponsor this project

    Packages

    No packages published

    Contributors12


    [8]ページ先頭

    ©2009-2025 Movatter.jp