app.get('/users', (req, res) => { res.json([{ name: 'John', age: 30 }, { name: 'Jane', age: 25 }]); });
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine that allows developers to create scalable and high-performance server-side applications. Node.js provides an event-driven, non-blocking I/O model that makes it lightweight and efficient.
const express = require('express'); const app = express();
describe('Greet function', () => { it('should greet a person', () => { assert.strictEqual(greet('John'), 'Hello, John!'); }); }); node.js beyond the basics pdf
Node.js provides various testing frameworks, including Mocha and Jest.
To start a new Node.js project, create a new directory and initialize a new project using npm init . This will create a package.json file that will be used to manage dependencies and scripts.
// Using callbacks fs.readFile('file.txt', (err, data) => { if (err) { console.error(err); } else { console.log(data.toString()); } }); To start a new Node
// Using promises const fs = require('fs').promises; fs.readFile('file.txt') .then((data) => console.log(data.toString())) .catch((err) => console.error(err));
// Creating a module // greet.js module.exports = function greet(name) { console.log(`Hello, ${name}!`); };
const userSchema = new mongoose.Schema({ name: String, age: Number }); Express
Node.js can be used to build scalable and high-performance RESTful APIs. Express.js is a popular framework for building web applications in Node.js.
const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });
passport.use(new LocalStrategy((username, password, done) => { // Verify user credentials if (username === 'john' && password === 'password') { return done(null, { username: 'john' }); } else { return done(null, false); } }));
const assert = require('assert'); const greet = require('./greet');
// Using a module const greet = require('./greet'); greet('John'); // Output: Hello, John!