DM
Technical reference

NodeJS Cheatsheet

Run JavaScript outside the browser

Getting Started

Hello World

Prints 'Hello, World!' to the console in Node.js.

console.log('Hello, World!');

Running a File

Use `node app.js` in the terminal to run the file.

// Save as app.js
console.log('Run this file');

Modules

Import Built-in Module

Loads Node's built-in file system module.

const fs = require('fs');

Export & Import Custom Module

Create and use your own module.

// myModule.js
module.exports = function greet() { console.log('Hi'); };

// app.js
const greet = require('./myModule');
greet();

File System (fs)

Read File

const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

Write File

fs.writeFile('file.txt', 'Hello World', (err) => {
  if (err) throw err;
  console.log('File saved');
});

HTTP Server

Basic HTTP Server

const http = require('http');
const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello, World!');
});
server.listen(3000);

NPM Packages

Install a Package

Installs the axios HTTP client.

npm install axios

Use Installed Package

const axios = require('axios');
axios.get('https://api.github.com').then(res => console.log(res.data));

Asynchronous Code

Callback Example

function fetchData(callback) {
  setTimeout(() => {
    callback('Data loaded');
  }, 1000);
}
fetchData(console.log);

Promise Example

function fetchData() {
  return new Promise(resolve => setTimeout(() => resolve('Done'), 1000));
}
fetchData().then(console.log);

Async/Await

async function getData() {
  const data = await fetchData();
  console.log(data);
}
getData();

Environment Variables

Access .env Variables

Use the dotenv package to load environment variables.

require('dotenv').config();
console.log(process.env.MY_SECRET);