Understanding Node.js: A Beginner's Guide to JavaScript Runtime and Chrome V8 Engine Part 2
import/export using .mjs:
The .mjs file extension is used to indicate a JavaScript file that contains ECMAScript modules. ECMAScript modules are a standardized way of organizing and sharing code between different JavaScript files, and they are supported by most modern browsers and Node.js.
To import and export modules using .mjs files, you can use the import
and export
keywords in your JavaScript code.
Here's an example of how to export a module from a .mjs file:
// myModule.mjs
export function morningGreeting() {
console.log('Good Morning Dear');
}
export const nightGreeting = 'Good Night Dear';
And here's an example of how to import that module into another .mjs file:
// main.mjs
import { morningGreeting, nightGreeting } from './myModule.mjs';
morningGreeting(); // logs 'Good Monrning Dear'
console.log(nightGreeting ); // logs 'Good Night Dear!'
Note that when importing a module from a .mjs file, you need to specify the file extension in the import statement (e.g. import { nightGreeting } from './myModule.mjs'
), otherwise you may encounter errors.
Also, keep in mind that while.mjs files are a standardized way of working with ECMAScript modules, some older JavaScript tools and environments may not yet support them. If you encounter issues, you may need to use a different file extension or transpile your code to an earlier version of JavaScript that supports a different module system.
Working with json in Node.js:
Working with JSON (JavaScript Object Notation) in Node.js is quite straightforward, as node.js provides built-in support for working with JSON data, which is a lightweight data-interchange format that is widely used for data exchange between systems. Here are some ways to work with JSON in Node.js:
Parsing JSON data: To parse a JSON string into a JavaScript object, you can use the
JSON.parse()
method. For example:const jsonData = '{"name": "Chuma", "age": 34}'; const obj = JSON.parse(jsonData); console.log(obj.name); // logs "Chuma"
Converting JavaScript objects to JSON: To convert a JavaScript object to a JSON string, you can use the
JSON.stringify()
method. For example:const obj = { name: 'Chuma', age: 34 }; const jsonData = JSON.stringify(obj); console.log(jsonData); // logs '{"name":"Chuma","age":34}'
Reading JSON data from a file: To read JSON data from a file, you can use the
fs
module to read the file contents and then parse the JSON string usingJSON.parse()
. For example:const fs = require('fs'); const jsonData = fs.readFileSync('data.json', 'utf8'); const obj = JSON.parse(jsonData); console.log(obj.name); // logs "Chuma"
Writing JSON data to a file: To write JSON data to a file, you can convert the JavaScript object to a JSON string using
JSON.stringify()
and then use thefs
module to write the string to a file. For example:const fs = require('fs'); const obj = { name: 'Chuma', age: 34 }; const jsonData = JSON.stringify(obj); fs.writeFileSync('data.json', jsonData);
These are just a few examples of how to work with JSON data in Node.js. There are many other libraries and tools available that can help you work with JSON data more efficiently and effectively, depending on your specific needs.
Built-in Modules in Node.js:
Node.js comes with many built-in modules that provide a wide range of functionality, including networking, file I/O, cryptography, and more. Here are some of the most commonly used built-in modules in Node.js along with examples of how to use them:
fs
module: Thefs
module provides an API for working with the file system. Here's an example that reads the contents of a file:const fs = require('fs'); fs.readFile('file.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); });
http
module: Thehttp
module provides an API for making HTTP requests and creating HTTP servers. Here's an example of creating an 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, () => { console.log('Server running on port 3000'); });
https
module: Thehttps
module provides similar functionality to thehttp
module, but for HTTPS connections. Here's an example of making an HTTPS request:const https = require('https'); https.get('https://www.microsoft.com', (res) => { console.log('statusCode:', res.statusCode); console.log('headers:', res.headers); res.on('data', (d) => { process.stdout.write(d); }); }).on('error', (e) => { console.error(e); });
crypto
module: Thecrypto
module provides an API for working with cryptographic functions, such as hashing, encryption, and decryption. Here's an example of hashing a password:const crypto = require('crypto'); const password = 'mypassword'; const hash = crypto.createHash('sha256').update(password).digest('hex'); console.log(hash);
path
module: Thepath
module provides utilities for working with file paths. Here's an example of joining two file paths:const path = require('path'); const dir = '/usr/local'; const file = 'index.html'; const filePath = path.join(dir, file); console.log(filePath);
os
module: This module provides information about the operating system. Here's an example of how to get information about the CPU using theos
module:const os = require('os'); console.log(os.cpus()); // logs an array of objects, where each object represents a single CPU/core available on the system. const totalMemory = os.totalmem(); console.log(totalMemory); // logs total memory in bytes
events
module: This module provides an API for working with events. Here's an example of how to create an event emitter and listen for an event using theevents
module:const EventEmitter = require('events'); const myEmitter = new EventEmitter(); myEmitter.on('hello', () => { console.log('Hello, World!'); }); myEmitter.emit('hello');
These are just a few examples of the built-in modules available in Node.js. There are many other modules available, each offering its own set of functionality to developers.
Conclusion
The use of ECMAScript modules with the .mjs file extension is a standardized way of organizing and sharing code between different JavaScript files in modern browsers and Node.js. To work with JSON in Node.js, you can use built-in methods like JSON.parse() to parse JSON strings and JSON.stringify() to convert JavaScript objects to JSON strings. Additionally, Node.js comes with built-in modules that provide a wide range of functionality such as the fs module for working with the file system, the http/https modules for making HTTP/HTTPS requests, the crypto module for working with cryptographic functions, the path module for working with file paths, and the os module that provides information about the operating system. These built-in modules can be used to perform a variety of tasks, depending on your specific needs.
Overall, the information provides a brief introduction and examples of these topics that can serve as a starting point for further exploration and development with JavaScript and Node.js.