[Golang] Concatenate JavaScript Files


Concatenate JavaScript files via Golang.

js.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package concat

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
)

func ConcatenateJS(dirPath string) []byte {
	var js_code []byte
	// walk all files in directory
	filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
		if !info.IsDir() && strings.HasSuffix(info.Name(), ".js") {
			println("concatenating " + path + " ...")
			b, err := ioutil.ReadFile(path)
			if err != nil {
				return err
			}
			js_code = append(js_code, b...)
		}
		return nil
	})
	return js_code
}
js_test.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package concat

import (
	"io/ioutil"
	"testing"
)

func TestConcatenateJS(t *testing.T) {
	b := ConcatenateJS("/home/siongui/dev/pali/common/app/scripts/")
	t.Log(string(b))
	ioutil.WriteFile("all.js", b, 0644)
}

Tested on: Ubuntu Linux 15.10, Go 1.6.


References:

[1][Python] Online Concatenate and Compress JavaScript Files
[2][Golang] Walk All Files in Directory
[3]go - How to read/write from/to file? - Stack Overflow
[4]ioutil - The Go Programming Language