Node.js Cheat Sheet
Node.js Basics
Installing Node.js
To install Node.js, follow these steps:
Running Node.js
To run a Node.js script, open a terminal or command prompt and type:
node script.js
Replace script.js with the name of your script file.
Node.js REPL
REPL stands for Read-Eval-Print-Loop. It is a simple program that takes your input, evaluates it, and returns the result.
To start the Node.js REPL, open a terminal or command prompt and type:
node
You can then enter JavaScript code and see the results immediately. To exit the REPL, press CTRL + C twice.
Modules in Node.js
In Node.js, a module is a reusable block of code that can be exported and used in other parts of your application. There are two types of modules:
To include a module in your application, use the require function:
const fs = require('fs');
To create and export a custom module, use the module.exports object:
module.exports =
sayHello: function() {
console.log('Hello');
}
};
To include and use the custom module in another file, use the require function:
const myModule = require('./myModule')
myModule.sayHello(); // Outputs: "Hello";
Node.js Events
Node.js has a built-in events module that allows you to create and handle custom events in your application.
To use the events module, you first need to require it:
const events = require('events');
You can then create a new event emitter object:
const emitter = new events.EventEmitter();
To handle an event, use the on function:
emitter.on('customEvent', (message) =>
? console.log(message);
});
To emit an event, use the emit function:
emitter.emit('customEvent', 'Hello World'); // Outputs: "Hello World"
Node.js Streams
Node.js streams are a way to handle reading and writing data in a continuous and efficient manner. Streams are a way to process data in chunks as they are available, rather than reading or writing the entire dataset at once. This makes them particularly useful when working with large amounts of data or when processing data in real-time.
There are four types of streams in Node.js:
To use streams in Node.js, you can create a stream object and use methods to read from or write to the stream. Here is an example of using a readable stream to read data from a file:
const fs = require('fs');
const readableStream = fs.createReadStream('/path/to/file.txt', 'utf8');
readableStream.on('data', (chunk) => {
? console.log(chunk);
});
readableStream.on('end', () => {
? console.log('Finished reading data');
});
In this example, we are creating a readable stream from a file and setting the encoding to utf8. We then attach two event listeners to the stream. The data event is fired whenever a chunk of data is available to read, and the end event is fired when the entire file has been read.
Here is an example of using a writable stream to write data to a file:
const fs = require('fs');
const writableStream = fs.createWriteStream('/path/to/file.txt');
writableStream.write('Hello, world!');
writableStream.write('This is a test.');
writableStream.end();
In this example, we are creating a writable stream to a file and writing two chunks of data to the stream. We then call the end method to signal that we are finished writing to the stream.
Overall, streams provide an efficient and flexible way to handle data in Node.js, especially when working with large datasets or real-time data processing.
Working with Files in Node.js
The fs (file system) module is a built-in module in Node.js that provides functions for working with files.
To read a file, you can use the fs.readFile function:
const fs = require('fs');
fs.readFile('/path/to/file.txt', 'utf8', (err, data) => {
? if (err) throw err;
? console.log(data);
});
To write to a file, you can use the fs.writeFile function:
领英推荐
const fs = require('fs');
fs.writeFile('/path/to/file.txt', 'Hello World', (err) => {
? if (err) throw err;
? console.log('The file has been saved!');
});
HTTP Server with Node.js
The http module is a built-in module in Node.js that provides functions for creating an HTTP server.
To create an HTTP server, use the http.createServer function:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
});
server.listen(3000, '127.0.0.1');
console.log('Server running at https://127.0.0.1:3000/');
This creates an HTTP server that listens on port 3000 and sends a response with the message "Hello World" when a request is received.
Express.js
Express.js is a popular Node.js framework that simplifies the development of web applications and APIs.
To install Express.js, use the following command:
npm install express
To create an Express.js app, require the express module and create an instance of the app:
const express = require('express');
const app = express();;
To handle HTTP requests, use the app.get function:
app.get('/', (req, res) => {
? res.send('Hello World');
});
To start the server, use the app.listen function:
app.listen(3000, () =>
? console.log('Server running on port 3000');
});
NPM (Node Package Manager)
NPM is a package manager for Node.js that allows you to install and manage third-party packages (libraries and tools) in your Node.js projects.
To install a package, use the following command:
npm install package-name
To install a package and save it as a dependency in your project's package.json file, use the --save flag:
npm install package-name --save
To install a package and save it as a dev dependency in your project's package.json file, use the --save-dev flag:
npm install package-name --save-dev
To update a package to the latest version, use the following command:
npm update package-name
To uninstall a package, use the following command:
npm uninstall package-name
Working with Databases in Node.js
There are many database systems that you can use with Node.js, such as MySQL, MongoDB, and PostgreSQL.
To connect to a database in Node.js, you will need to install a database driver. For example, to connect to a MySQL database, you can use the mysql package:
npm install mysql
To connect to the database, you will need to require the database driver and create a connection:
const mysql = require('mysql');
const connection = mysql.createConnection({
? host: 'localhost',
? user: 'username',
? password: 'password',
? database: 'database_name'
});
connection.connect();
To execute a query, use the connection.query function:
connection.query('SELECT * FROM users', (err, rows, fields) => {
if (err) throw err;
console.log(rows);
});
To close the connection, use the connection.end function:
connection.end();
Debugging Node.js Applications
To debug a Node.js application, you can use the debugger statement in your code and run the application with the --inspect flag:
node --inspect script.js
This will start the Node.js debugger and you can use the Chrome DevTools to debug your code.
Alternatively, you can use a debugging tool such as the debug package:
npm install debug
To use the debug package, require it in your code and use the debug function:
const debug = require('debug')('app:debug');
debug('Debug message');
To enable debugging, set the DEBUG environment variable:
DEBUG=app:* node script.js
This will enable debugging for all modules with the app: namespace.
Additional Resources
MERN Stack Developer | MCA Student | Open to Web Development Projects.
5 个月Thomas , this cheat sheet is really amazing . U know its better if u make it more interactive like
Information Security Engineer
1 年Nice writeup Jomas! Thanks for sharing