vimwiki/lang/Node.js.wiki

56 lines
1.5 KiB
Plaintext
Raw Normal View History

2021-11-19 02:00:01 +00:00
= Node.js =
Node.js is an Asynchronus, event driven javascript runtime. On line the command
is `node`.
== Hello World ==
2021-11-19 02:15:01 +00:00
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")
}}}
== 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#)