CSCI 3100 Tutorial 3 JavaScript & Node.js Presented by SU Yuxin Department of Computer Science and Engineering The Chinese University of Hong Kong 1 Outline • • • • • Introduction to JavaScript JavaScript Basic Advanced Features of JavaScript Introduction to Node.js A Secret… 2 Do you know JavaScript? Java JavaScript 3 What is JavaScript Script Language • Shell • C# Dynamic Type • Python • Java Objectedoriented • C++ •C Unique Feature: 4 Where to use JavaScript • The whole picture: browser modify/create/delete data transmit HTML CSS JavaScript HTML5 Server Side • PHP • Rails on Ruby • JavaScript ??? 5 JavaScript Basic • • • • • Output Variable & Arithmetic Object & Array Function IF & Loop statement 6 JavaScript Basic Output • No printf()! • Use console.log() / alert() instead. 7 JavaScript Basic Variable & Arithmetic Number can be integer or floating point String can be in single or double quotes If there is no initial value, the value is undefined String concatenation Integer Arithmetic 8 JavaScript Basic Object You can use any property without declaration. You can also treat function as a property of the object, and assign it like this. 9 JavaScript Basic Array Create an array Initialization Access an array Use it as a dictionary Multi-type Build-in functions and properties 10 JavaScript Basic Function Declaration Argument & Return value 11 JavaScript Basic IF & Loop statement FOR Loop IF statement WHILE Loop Note: Anything defined will be treat as true. Undefined will be treat as false. 12 ADVANCED FEATURES 13 Regular Expression • First-class citizen in JavaScript • Create: var pattern = /g$/; Any expression ended with letter ‘g’ var pattern = new RegExp(“g$"); • Use: "Software Engineering".search(pattern); text.replace(/javascript/gi, "JavaScript"); "1 plus 2 equals 3".match(/\d+/g); "123,456,789".split(","); 14 Prototype • function Range(from, to) { It looks like the definition this.from = from; this.to = to; of class! } Range.prototype = { includes: function(x) { return this.from <= x && x <= this.to; }, foreach: function(f) { for(var x = Math.ceil(this.from); x <= this.to; x++) f(x); }, toString: function() { return "(" + this.from + "..." + this.to + ")"; } }; // Here are example uses of a range object var r = new Range(1,3); // Create a range object r.includes(2); // => true: 2 is in the range r.foreach(console.log); // Prints 1 2 3 console.log(r); // Prints (1...3) 15 Callback Function • function main(callback) { alert("I am main function"); alert("Invoke callback function.."); callback(); } function b(){ alert("I am callback function: b"); } function c(){ alert("I am callback function: c"); } • Function is passed as a parameter • User-defined behavior at the end of a function or “event”. function test() { main(b); main(c); } 16 Advanced Array Methods var data = [1,2,3,4,5]; //compute the sum of the array elements var sum = 0; data.forEach(function(value) { sum += value; }); console.log("The sum is " + sum.toString()); • Other similar functions: – – – – map() filter() every() some() //Increase Each element by 1 data.forEach(function(v, i, a) { a[i] = v + 1; }); 17 Asynchronous // Synchronously read a file. Pass an encoding to get text instead of bytes. var text = fs.readFileSync("config.json", "utf8"); // Asynchronously read a binary file. Pass a function to get the data fs.readFile("image.png", function(err, buffer) { if (err) throw err; // If anything went wrong process(buffer); // File contents are in buffer }); 18 INTRODUCTION TO NODE.JS 19 Where to run my code? 20 Where to run my code?(con’d) • Chrome: • Node: • $ node test.js 21 IDE: Jetbrains WebStorm http://www.jetbrains.com/webstorm/ You can register a student account with your cuhk.edu.hk email 22 What the Node.js is designed for? 23 Installation and HTTP setup • Install Node.js from http://nodejs.org/download/ • Use it to create a HTTP server: – 1. In cmd of Windows, type: npm install http-server –g • If you have a HTTP proxy, type this first: • npm config set proxy http://proxy.company.com:port – 2. Start HTTP server: http-server /path • The path is the folder you want to share in web • Your folder must have some files before it works, i.e. index.html (put ‘it works’ in it) – 3. Open http://localhost:8080/ in your browser 24 Modules https://www.npmjs.com/ 25 Event-based Design var events = require("events"); var emitter = new events.EventEmitter(); var username = "colin"; var password = "password"; // an event listener emitter.on("userAdded", function(username, password) { console.log("Added user " + username); }); // add the user // then emit an event emitter.emit("userAdded", username, password); 26 More details will coming at further tutorial 27 Finally, the secret is… • If you think JavaScript is powerful… • But, – Too difficult to learn? – Too complex to write? – Too ugly to read? Reference: Google it! 28