Basics of Node.js
Basics of Node.js:
Node.js is a type of JavaScript runtime environment that can help you run JavaScript inside the server.
It is based on V8 JavaScript virtual machine and aims to give environment to use JavaScript beyond browser environments.
Setting Up Node.js:
First, you need to install Node.js on your machine. You can download it from the official website: Node.js.
Creating a Simple Node.js Script:
- Create a new file with a .js extension, for example, app.js.
- Open it in a code editor and write a simple script, like:
console.log("Hello, Node.js!");
Running Your Script:
- Open a terminal and navigate to the directory where your script is located.
- Run the script using the node command:
node app.js
Modules in Node.js:
Node.js uses a module system to organize code. You can create modules and use them in other files. For example:
- Create a file named myModule.js:
// myModule.js
const greeting = "Hello from my module!";
module.exports = greeting;
- Use this module in another file, e.g., app.js:
// app.js
const myModule = require('./myModule');
console.log(myModule);
npm (Node Package Manager):
- Node.js comes with npm, which is a package manager for JavaScript. You can use it to install and manage third-party libraries.
- For example, to install the lodash library:
npm install lodash
Then, in your script:
const _ = require('lodash');
console.log(_.shuffle([1, 2, 3, 4]));
HTTP Server with Node.js:
Node.js can be used to create web servers. Here's a simple example using the built-in http module:
// server.js
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, Node.js Server!');
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
Run the server with:
node server.js
Visit http://localhost:3000 in your browser to see the response.
Here is a set of elementary instructions with Node by means of which you can start your training: js.
No more when it comes to asynchronous functions using callbacks, Promises, and async/await and accessing the file system and other external libraries/freeware such as Express framework.