Common used commands, methods, and concepts of Node.js

Photo by Andrew Neel on Unsplash

Common used commands, methods, and concepts of Node.js

ยท

2 min read

Setting up a Node.js project:

  • Create a new project: npm init
  • Install dependencies: npm install
  • Create an entry point file (e.g., index.js)

Working with modules:

  • Importing modules: const moduleName = require('module')
  • Exporting from a module: module.exports = exportedObject

Working with the file system:

  • Reading a file: fs.readFile(path, encoding, callback)
  • Writing to a file: fs.writeFile(path, data, callback)
  • Checking if a file/directory exists: fs.existsSync(path)

HTTP server and requests:

  • Creating an HTTP server: http.createServer(callback)
  • Handling requests and responses: request and response objects in the server callback
  • Making HTTP requests (external): http.get(url, callback) or https.get(url, callback)

Working with the command line:

  • Accessing command-line arguments: process.argv
  • Exiting a Node.js program: process.exit()

Working with packages and dependencies:

  • Installing a package locally: npm install
  • Installing a package globally: npm install -g
  • Uninstalling a package: npm uninstall

Asynchronous programming:

  • Using callbacks: function callback(err, result) { ... }
  • Using Promises: new Promise((resolve, reject) => { ... })
  • Using async/await: async function functionName() { ... }

Debugging and logging:

  • Printing to the console: console.log('message')
  • Debugging with breakpoints: debugger statement
  • Using a debugger: node inspect or node --inspect

Package.json scripts:

  • Defining custom scripts: "scripts": { "start": "node index.js" }
  • Running scripts: npm run

NPM commands:

  • Installing all dependencies: npm install
  • Updating packages: npm update or npm update
  • Listing installed packages: npm list
  • Searching for packages: npm search
ย