Evan Shortiss
Software Engineer and Mobile Developer. Works at FeedHenry
with
var tcp = require('net');
var socket = tcp.createConnection(3000, '127.0.0.1');
// If there's no activity or failure to connect
// in ten seconds emit a timeout error and bail
socket.setTimeout(10*1000);
// Handle a timeout error
socket.on('timeout', function () {
console.error('Socket timeout!')
});
// Handle the 'connect' event and
// send a message, then close the socket
socket.on('connect', function () {
socket.write('Hello!', 'utf8');
// Send data and close the socket
socket.end('Goodbye!', 'utf8');
});
var http = require('http');
var port = 8080;
var server = new http.Server();
// Event handling functions...
// Handle events
server.on('request', handleRequestFn);
server.on('connection', handleConnectionFn);
server.on('clientError', handleClientErrorFn);
server.on('close', handleCloseFn);
server.on('listening' handleListeningFn);
// ...etc
server.listen(port);
var fs = require('fs');
// This is asynchronous, it's non-blocking! When it finishes
// the provided callback is triggered with end results at a later point
fs.readFile('README.md', function(err, data) {
if (err) {
// Handle the error
console.error(err)
} else {
console.log(data)
// Do further logic
}
});
console.log('This prints before the README.md is printed.');
// This is synchronous. It's blocking!
var data = fs.readFileSync('README.md', 'utf8'); // This might take a while...
console.log(data);
console.log('This prints after the readFileSync finishes.');
Runtime environment for Node.js code
$ node myscpript.js
Events (events)
TCP (net)
UDP (dgram)
HTTP (http)
HTTPS (https)
FileSystem (fs)
Utilities (util)
$ npm init $ npm install request $ npm install -g jshint $ npm search jquery $ npm uninstall request
(Over 100,000 modules available!)
The bread and butter of well written applications!
Write programs that do one thing and do it well.
Write programs to work together.
Write programs to handle text streams, because that is a universal interface.
$npm install {module-name} --save
$npm uninstall {module-name}
$npm install {module-name} --save-dev
"scripts" {
"test": "mocha ./test -R spec"
"format": "jshint ./src/*.js"
}
$ npm run-script format $ npm run-script test
/**
* @filename: math.js
*/
// This is private
function inverse (num) {
return num * -1;
}
// A public function!
exports.subt = function (a, b) {
return a - b;
};
// Another public function with a local reference
var add = exports.add = function (a, b) {
return a + b;
};
exports.inverseOfAddition = function (a, b) {
return inverse(add(a, b));
};
/**
* @filename: main.js
*/
var myMath = require('./math.js');
var a = 10;
var b = 34.2;
myMath.add(a, b); // ==> 44.2
myMath.subt(a, b); // ==> -24.2
myMath.inverseOfAddition(a, b); // ==> -44.2
/**
* @filename: User.js
*/
function User (name, age) {
this.name = name;
}
// Set the exports object to our class
module.exports = User;
User.prototype.getName = function () {
return this.name;
};
// ===================================
/**
* @filename: main.js
*/
var User = require('./User');
var u = new User('Evan');
"With great power comes great responsibility"
// The callback we'll use
function callMeOnceComplete (err, res) {
if (err) {
console.error(err);
} else {
console.log(res);
}
}
// An async function that provides results via callback
callSomeAsyncOperation(callMeOnceComplete);
var fs = require('fs')
// Asynchronously reads a JSON file and parses it
function readJsonFile (filepath, callback) {
fs.readFile(filepath, function (err, data) {
if (err) {
return callback(err, null);
}
try {
callback(null, JSON.parse(data);
} catch (e) {
callback(e, null);
}
});
}
// Avoid this situation! It's untidy.
firstAsync(data, function (res1) {
secondAsync(res1, function (res2) {
thirdAsync(res2, function (res3) {
fourthAsync(res3, function (finalResult) {
// Do something with the result
});
});
});
});
var async = require('async');
// Run provided functions in sequence
async.series([
firstAsync,
secondAsync,
thirdAsync,
fourthAsync
], function (err, res) {
// Called when all other functions are complete
});
// Don't ty this at home folks!
var fs = require('fs')
function saveUserFiles (fileList)
// This will run all the writes in parallel...
// ... what will happen if we have 5000 files to write!?
fileList.forEach(function (data) {
fs.writeFile(data, function (err) {
// This will be called for each item!
// This is an anti-pattern!
if (err) {
console.error(err);
} else {
console.log('Saved %j', data);
}
});
});
}
var async = require('async');
var fs = require('fs');
var MAX_CONCURRENCY = 10;
function writeToFile (listItem, cb) {
fs.writeFile(listItem.data, cb);
}
function saveUserFiles (fileList, callback) {
// Write up to MAX_CONCURRENCY files at a time
// Each file is passed to the writeFile function
// When all writes are complete the callback is called
async.eachLimit(fileList, MAX_CONCURRENCY, writeToFile, callback);
}
By Evan Shortiss
A basic overview of Node.js core concepts.
Software Engineer and Mobile Developer. Works at FeedHenry