vimwiki/tech/Node.js.wiki

149 lines
4.3 KiB
Plaintext

= Node.js =
Node.js is an Asynchronus, event driven javascript runtime. On line the command
is `node`.
== Hello World ==
1) Create a file called `index.js`. This is always the entry point (similar to
a main()).
2) Place code. It is interpreted the same as if it were in the browser. For
example,
{{{
console.log("hello world")
}}}
== Modules Available ==
All modules are included by using the `require('MODULE')` syntax
| Module | Use |
----------------
| HTTP | classes, methods, etc to make Node.js server |
| uitl | utility functions for developers |
| fs | filesystem |
| url | parse urls |
| query string | work with the query string |
| stream | handling streaming data |
| zlib | compression |
== Events ==
Events are times when certain things happen. We can do things on those events
by using a callback. This is accessed via the process object. For example,
{{{
process.on('exit', function() {
Console.log("Goodbye!");
});
}}}
Will print goodbye to the console when the program terminates. process.on takes
two paramaters, the event name '`exit`', and the function (or lambda).
To create an event, we can use the Event Emitter, a node.js builtin. The
following example is an annotated example of exactly that.
{{{
//pull in the event emitter dependency
const { EventEmitter } = require('events');
//create the event emitter
const eventEmitter = new EventEmitter();
//create the callback 'lunch'
eventEmitter.on('lunch', function() {
console.log("Lunch time");
});
//trigger the callback function
eventEmitter.emit('lunch');
}}}
As you can see, this is a similar concept to something like function pointers,
where a pointer is assigned then later called through the pointer.
== File system ==
The file system can be read in two modes, either in a block or non blocking
mode (similar to async calls in C#)
Below is an example of exactly that. The 'Sync' calls are ones that are done in
a blocking manner
{{{
//import read file
const { readFile, readFileSync } = require('fs');
//read the file, blocking
const txt = readFileSync('./sample.txt', 'utf8');
console.log(txt);
//or read the file on a seperate thread
//the third argument is the file name, encoding, then the function (which gets
//passed both the error object, and the contents of the file)
readFile('./sample.txt', 'utf8', (err, txt) => {
//stuff to do after we get the file
console.log(txt)
});
console.log('this is called after the fact');
}}}
== URL ==
Node.js can help you parse URLs and resolve where they lead. The module is
build into node.js. The following example code would print the hostname,
filepath, and search string (as an object)
{{{
//import express and url
const express = require('express');
const url_lib = require('url');
//create objects
const app = express();
const url = 'http://www.clortox.com/posts/';
const parsed_url = url_lib.parse(url, true);
//express listener
app.get('/', async (request, response) =>{
response.send(parsed_url.path);
});
//listen
app.listen(process.env.PORT || 3000, () => console.log('Available on localhost:3000'));
}}}
== Packages ==
Node.js's package manager is npm. It can download packages for you to use in
your project. To start using npm in a project, run `npm init -y` to setup a
package.json file, which is how npm keeps track of files it needs. Now to
install a framework (for example, express), run `npm install express`, and
thats all that is needed
To include a package (which includes the several built in packages), use the
`require()` syntax, and pass it a string argument of the name of the module.
This system is how you can use several files on one project. To include a
module called 'my-module', you first create a my-module.js file, the add this
to the top of your code
{{{
const myModule = require('./my-module');
console.log(myModule);
}}}
Then in the module file you must export code from it. In the module file, add
the following
{{{
module.exports = {
myvar : 'some value'
}
}}}
Now myModule.myvar will return 'some value'. You can use functions and the like
here to make easy to import functionality.