-
Notifications
You must be signed in to change notification settings - Fork 0
Node.js
Kyle Coberly edited this page Aug 6, 2017
·
1 revision
- Node is fast
- Non-blocking IO
- Uses Google's V8 engine
- One language to rule them all
- Good standard library
- npm
- You have to think in async
- Has maturity issues
- Callback hell
- JavaScript has quirks
- Single-threaded has advantages over threaded
- Node has an event loop handling all requests, which it delegates to POSIX async threads
- Restaurant metaphor -> one waiter who just takes orders and delivers food vs. 10 waiters who do everything
- Don’t use node for CPU intensive tasks (video processing).
- V8 (the engine)
- Libev: The event loop
- LibEio: Async I/O
- LibUv: Abstraction on libEio, libev, etc
- A standard library
-
process- Running process -
require- Function to require package -
console-
consoleobject is similar, but different -
console.errorprints tostderr -
console.trace()to show stack trace
-
global-
http- Has to be imported - No
document,window,DOM
var express = require("express");- Can be a JS file or a JSON file
- If the thing isn't a file, it looks inside for an
index.jsfile. - Don't have side effects in your modules.
- 4 ways to require:
-
require("fs")- Core module or fromnode_modulesfolder -
require("./something")- For arbitrary files -
require("../config.json")- For arbitrary files -
requirereturns whatever is hanging off ofmodule.exportsin that file
-
- You can immediately invoke modules
- You can export anything (function, object, whatever)
- Simple Object API
- Hide private variables
- Returning an object literal
- Revealing Module
var MyModule = (function(){
function hiddenMethod() {
return "hey";
}
return {
publicMethod: privateMethod
};
})();
MyModule.privateMethod(); // undefined
MyModule.publicMethod(); // "hey"- Modules are cached- it's the same object!! Returning just an object is a singleton.
- Object constructor (returns an object with a prototype chain)
- Is the tool,
npm- Has publishing tools (can include tasks)
- Is the site, https://www.npm.org
- Is the registry (which is not the actual packages, just pointers to them)
- Can be public or private
- Project Metadata is in
package.json- Create one with
npm init
- Create one with
- Setting up
npmdefaults:npm set init.author.name "Kyle Coberly"npm set init.author.email "[email protected]"npm set init.author.url "www.kylecoberly.com"
- Installing locally
-
npm install package_nameto try -
npm install --save package_nameto install production dependency -
npm install --save-dev package_nameto install development dependency
-
- Installing globally
npm install -g package_name
-
npm ls,npm -gto list installed packages
-
~1,~1.1goes for highest minor or patch version -
npm shrinkwrap- Snapshots every version -
npm search- Looks for packages, kind of sucks, use Google -
npm update- Updates registry -
npm rm --save- Deletes a package
- The process object has the environment variables, can kill processes, access the shell, etc.
process.env; // {
SHELL: "/bin/zsh",
USER: "kylecoberly",
HOME: "/home/kylecoberly",
PORT: 3000,
NODE_ENV: "development"
}- Get arguments via
process.argv- Takes the command line as space-delimited tokens
- Doesn't parse anything
- Includes
node - Returns array
- To kill node:
-
process.exit(0)for success -
process.exit(127)for failure
-
- To respond to signals:
process.on("eventName", function(error){
console.log("error", error);
});- POSIX codes from OS:
SIGINT,ENONT,EADDRINUSE
- Write and handle HTTP/HTTPS requests
- Use package to auto load on change = nodemon, eg- nodemon server.js
var http = require("http");
var server = http.createServer(function handleRequests(request, response){
response.writeHead(200, {
"Content-Type": "text/plain",
"X-My-Thing": "The internet"
});
response.end("Hello world!");
});
server.listen(3000, "127.0.0.1", function(){
console.log("It's up!");
})- Allows you to create sub-processes.
-
spawnis an instance of theChildProcessclass. Close the input stream to allow the spawned process to continue running.
var execute = require("child_process").exec;
var ps = execute("ps aux", function (err, stdout, stderr){
// Do something
}; var spawn = require("child_process").spawn;
var someEvent = spawn("someEvent", ["something"]);
someEvent.stdout.on("data", function(data){
tee.stdin.write(data);
};-
STDIN,STDOUT,STDERR - Event emitters that have standard events. They are pluggable.
-
.data(),.write(),.end(),.pipe()
-
- Whether it's readable/writeable can depend on perspective
-
STDOUTandSTDERRare both blocking. Special streams! -
stream.ttywill tell you if the user is using it directly, rather than a program
- To listen in on data from stdin, use the
dataandendevents -
datais input fed to the program. This may trigger multiple times. -
endsays the you’re done reading.STDINis paused by default
-
write()to write toSTDOUT
- For logging, usually
- Buffers are chunks of binary data in memory
- For larger data sets or if you don’t how much of something you'll have:
buffer = new Buffer(26); buffer.toString("utf8", 0, 5);
- File handling can/should be non-blocking. That's what makes it "web scalable".
- Check that it exists before you start reading
- Don't respond with errors for files that users don't have permissions to access
- File system is core module
- Race conditions = When something is no longer true after you check it
- Don’t use the sync version of the fs methods! Won’t scale!
fs.readFile("file/path", {options}, function(error, contents){
if (error){
// throw...
}
console.log(contents);
});fs.writeFile();fs.appendFile();fs.exists();fs.stats.isFile()fs.stats.isDirectory()fs.stats.isSocket()fs.stats.sizefs.stats.mtimefs.link(“src”, “dest”, “file” callback);fs.unlink(); // deletefs.mkdir();fs.readdir();fs.rmdir();
process.nextTick();- All async functions require callbacks.
- Callback hell - fight with event emitters, named functions, library, or promises
-
callbackandnextmean the same thing
-
- Event emitter is a string with a corresponding callback
- Events are an imported module
- Can also inherit from util.
emitter.listeners(eventName)emitter.on(eventName, listener)emitter.once(eventName, listener)emitter.removeListener(eventName, listener);
- Install driver module
- Create a connection
- Connect it
- Query it
- Require MongoClient
- Declare URL
- Connect with mongo
- MongoLab = free cloud instances
- Node is fast, but single-threaded. This means every request uses the same process.
- Non-blocking code ensures that something else is handling async requests, usually via callbacks.
- unclustered node app only using one core.
- Clustered node app can use every core.
-
clustermodule - Call cluster.fork() once per CPU core
- Strongloop Process Manager does this for you
- Scalability is gained by putting a load balancer in front of multiple servers.
- KISS Servers: small core, small modules (Node core)
- Convention: follow the leader, steep learning curve (Express, restify, Total.js)
- Configuration: open path, manual effort for advanced (Hapi, Kraken)
- ORM & Isomorphic: model-driven, shared code, steep learning (Loopback, Sails, Meteor)
- One way, part of HTML5
EventSource- Add event listeners in your code
- Two newlines is “end of message”
- Don’t close the connection
- Accept-Type: Event-Stream
-
DEBUGlibrary - built-in debugger
- Node Inspector = Chome dev tools for node. Use Chrome debugger, etc.