modules


Node.js

  1. # initializing metadata and dependencies file (package.json)
  2. $ npm init
  3. # installing a module
  4. $ npm install moment --save
  5. # updating a module
  6. $ npm install moment@latest --save
  7. # removing a module
  8. $ npm uninstall moment --save
  9. # pruning modules (removing unused modules)
  10. $ npm prune
  11. # publishing a module
  12. $ npm publish
  1. // importing a module
  2. const moment = require('moment')
  3. const now = moment().unix()
  4. console.log(now)

Output

  1. 1546595748
  1. // exporting a module
  2. module.exports = {
  3. greet(name) {
  4. console.log(`hello ${name}`)
  5. }
  6. }
  1. // importing exported module
  2. const greeter = require('./greeter')
  3. greeter.greet('bob')

Output

  1. hello bob

Go

Setup

  1. # enable Go modules support
  2. GO111MODULE=on
  3. # initializing dependencies file (go.mod)
  4. $ go mod init
  5. # installing a module
  6. $ go get github.com/go-shadow/moment
  7. # updating a module
  8. $ go get -u github.com/go-shadow/moment
  9. # removing a module
  10. $ rm -rf $GOPATH/pkg/mod/github.com/go-shadow/moment@v<tag>-<checksum>/
  11. # pruning modules (removing unused modules from dependencies file)
  12. $ go mod tidy
  13. # download modules being used to local vendor directory (equivalent of downloading node_modules locally)
  14. $ go mod vendor
  15. # publishing a module:
  16. # Note: Go doesn't have an index of repositories like NPM.
  17. # Go modules are hosted as public git repositories.
  18. # To publish, simply push to the repository and tag releases.
  1. package main
  2. import (
  3. "fmt"
  4. // importing a module
  5. "github.com/go-shadow/moment"
  6. )
  7. func main() {
  8. now := moment.New().Now().Unix()
  9. fmt.Println(now)
  10. }

Output

  1. 1546595748
  1. package greeter
  2. import (
  3. "fmt"
  4. )
  5. // exporting a module (use a capitalized name to export function)
  6. func Greet(name string) {
  7. fmt.Printf("hello %s", name)
  8. }
  1. package main
  2. import (
  3. // importing exported module
  4. greeter "github.com/miguelmota/golang-for-nodejs-developers/examples/greeter_go"
  5. )
  6. func main() {
  7. greeter.Greet("bob")
  8. }

Output

  1. hello bob