Welcome to the ultimate Node.js cheat sheet, your comprehensive guide to mastering Node.js, whether you’re just starting out or looking to brush up on your knowledge. This post will cover installation, core modules, useful commands, and best practices for efficient Node.js development.
Getting Started with Node.js
Installing Node.js:
Download and install Node.js from nodejs.org. Choose the version recommended for most users, unless you have specific needs that require the latest features or earlier compatibility.
Verifying Installation:
Check that Node.js and npm (node package manager) were installed correctly by running:
npm -v
Key Node.js Commands
Start a Node.js Application:
Initialize a New Node.js Project:
Install a Package Locally:
Install a Package Globally:
Important Node.js Modules
File System (fs)
Read a file asynchronously:
fs.readFile(‘/path/to/file‘, ‘utf8‘, (err, data) => {
if (err) throw err;
console.log(data);
});
Write to a file asynchronously:
if (err) throw err;
console.log(‘File has been written!‘);
});
HTTP
Create an HTTP server:
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader(‘Content-Type‘, ‘text/plain‘);
res.end(‘Hello Worldn‘);
});
server.listen(3000, () => {
console.log(‘Server running at http://localhost:3000/‘);
});
Path
Manage file paths:
console.log(path.resolve(‘app.js‘)); // Resolves to absolute path
Debugging in Node.js
Basic Debugging:
Use console.log, console.error, and console.warn to output debugging information to the console.
Advanced Debugging:
Run Node.js in inspect mode and attach a debugger.
Environment Management
Setting Environment Variables:
Accessing Environment Variables in Node.js:
Working with npm
Update a Package:
List Installed Packages:
Uninstall a Package:
Conclusion
This Node.js cheat sheet is designed to help you quickly find the command or code snippet you need to enhance your development workflow. Whether you’re troubleshooting, setting up a new project, or learning the ropes, keep this guide handy to streamline your Node.js experience.
Stay curious and keep building amazing things with Node.js!