GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing zetcode.com — Node.js Tutorial - Introduction to Server-Side JavaScript Introduction to Node.jslast modified last modified October 18, 2023 Node.js tutorial is an introductory tutorial to Node.js. We describe Node.js and provide some Node.js code examples. Node.jsNode.js is an open-source, cross-platform JavaScript run-time environment. It was built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js was originally written by Ryan Dahl in 2009.
Node.js provides a rich library of various JavaScript modules, such as
Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft Windows, and Linux.
Node.js has a package manager called Node.js installationWe install the newest version of Node.js. Follow the installation instructions available on the Node.js website for your platform. Node.js first exampleWe create a simple console application. first.js
console.log("This is our first application");
The program prints a message to the console. $ node first.js This is our first application Node.js read contents of file
Node.js contains the words.txt
blue book pen dog computer screen We have a text file. Most functions in Node.js are asynchronous. The are non-blocking; i.e. they do not block the execution of the script. read_file.js
const fs = require('fs')
fs.readFile('words.txt', 'utf-8', (err, data) => {
if (err) throw err;
console.log(data);
});
console.log("Script continues...")
The example reads the contents of the const fs = require('fs');
We load the fs.readFile('words.txt', 'utf-8', (err, data) => {
The $ node read_file.js Script continues blue book pen dog computer screen The 'Script continues' is shown before the contents of the file. Node.js read directory synchronouslyNow we are going to read the contents of a directory. readdir_syn.js
const fs = require('fs');
readDirContentSync('.');
console.log("Ready.");
function readDirContentSync(mydir) {
const filenames = fs.readdirSync(mydir);
for (var i = 0; i < filenames.length; i++) {
console.log(filenames[i]);
}
}
The code example reads the contents of a directory synchronously. const filenames = fs.readdirSync(mydir);
We read the directory synchronously with for (var i = 0; i < filenames.length; i++) {
console.log(filenames[i]);
}
We loop through the array of file names and print them to the console. $ node readdir_syn.js builtins.js first.js links read_file.js readdir_asyn.js readdir_syn.js server.js todo words.txt Ready. With a synchronous function call, the 'Ready.' message is shown after the function finishes its execution. Node.js read directory asynchronouslyIn the next example, we read a directory asynchronously. readdir_async.js
var fs = require('fs');
fs.readdir(".", (err, filenames) => {
for (var i = 0; i < filenames.length; i++) {
console.log(filenames[i]);
}
console.log("Ready.");
});
The Node.js reading web page
In the following example we read a web page using a built-in read_webpage.js
const http = require('http');
const request = http.request({ hostname: 'webcode.me' }, (res) => {
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(chunk);
});
});
request.end();
request.on('error', (err) => {
console.log("Error occured\n");
console.error(err);
});
In the example, we use the $ node read_webpage.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My html page</title>
</head>
<body>
<p>
Today is a beautiful day. We go swimming and fishing.
</p>
<p>
Hello there. How are you?
</p>
</body>
</html>
We have received this small HTML page. Node.js install module with npm
Additional modules can be installed with $ mkdir builtmodtest $ cd builtmodtest/ $ npm init
We create a new project directory. With $ cat package.json
{
"name": "builtmodtest",
"version": "1.0.0",
"description": "Testing builtin modules",
"main": "main.js",
"scripts": {
"start": "node main.js"
},
"author": "Jan Bodnar",
"license": "ISC"
}
This is the initial $ npm install builtin-modules $ tree -L 1 . ├── main.js ├── node_modules ├── package.json └── package-lock.json
With the $ cat package.json
{
"name": "builtmodtest",
"version": "1.0.0",
"description": "Testing builtin modules",
"main": "main.js",
"scripts": {
"start": "node main.js"
},
"author": "Jan Bodnar",
"license": "ISC",
"dependencies": {
"builtin-modules": "^2.0.0"
}
}
The main.js
const builtmods = require('builtin-modules');
console.log(builtmods);
This is the $ npm start > [email protected] start /home/janbodnar/prog/nodejs/builtmod > node main.js [ 'assert', 'async_hooks', 'buffer', 'child_process', 'cluster', 'config', 'console', 'constants', ... ] Node.js server
We create a simple server with Node.js server.js
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {"Content-Type": "text/plain"});
res.end("Hello there\n");
});
server.listen(8000);
console.log("Server running at http://127.0.0.1:8000/");
The server sends a simple text message to the client. const http = require('http');
We load the const server = http.createServer((req, res) => {
res.writeHead(200, {"Content-Type": "text/plain"});
res.end("Hello there\n");
});
A server is created. It sends a text message to the client. server.listen(8000); The server listens on port 8000 on localhost. $ node server.js & $ curl localhost:8000 Hello there
We run the server and create a request with SourceIn this article we have introduced Node.js. We have created some code examples with Node.js. AuthorMy name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming. |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |