المعرفة:: NodeJS الحالة::مؤرشفة المراجع:: The Complete Node.js Developer Course 3rd Edition, coggro’s Notes, anuragkapur’s Notes
Importing Node.js Core Modules
- All modules of Node.js API, listed in docs here, are available globally, so they can be used without importing them e.g.
console.
console.log('Hello Node.js!')Core Modules and require
- Node.js comes with dozens of built-in modules. These built-in modules, sometimes referred to as core modules, gives access to tools for working with the file system, making http requests, creating web servers, etc.
- The module system is built around the
requirefunction. This function is used to load a module and get access to its contents.requireis a global variable provided to all your Node.js scripts.
const fs = require('fs');
fs.writeFileSync('notes.txt', 'Hello Note.js!');- The script above uses require to load in the
fsmodule. This is a built-in Node.js module that provides functions you can use to manipulate the file system. The script useswriteFileSyncto write a message tonotes.txt. - Note that we can have a different name for the variable
fsand the program would work, though it’s common to stick with the convention for all node modules we load.
fs.appendFileSync('notes.txt', 'Added text');Importing Our Own Files
requirecan also be used to load in JavaScript files created by us. All you need to do is providerequirewith a relative path to the script you want to load. This path should start with./and then link to the file that needs to be loaded in.
console.log('utils.js!')const checkUtils = require('./src/utils.js');
checkUtils();- The code above uses
requireto load in a file calledutils.jsin thesrcdirectory. It stores the module contents in a variable, and then uses the contents in the script. - Each module has its own scope with its own variables because Node.js scripts don’t share a global score. This means variables created in one scripts are not accessible in a different script. The only way to share values between scripts is by explicitly export what we need to use using
requirewithmodule.exports.
Exporting from Files
- Node.js provides the required script with a place to store values that should be exported as part of the library which is
module.exports. - In
utils.jsbelow. A function is defined and then assigned tomodule.exports. The value stored onmodule.exportswill be the return value for require when the script is imported. That means other scripts could load in the utilities to access the check function.
const getNotes = function () {
return 'Your notes...'
}
module.exports = getNotesconst getNotes = require('./notes.js')
const msg = getNotes()
console.log(msg)- It’s possible to export and import more than one variable from a module too using Object Destructuring and ES6 short-hand for object literals.
// file 1
// ...
export { utilslog, name }
// or
module.exports = {getNotes, addNotes}
// module.exports = {getNotes: getNotes, addNotes: addNotes}
// file 2
import { name, utilslog } from './utils.js'- We can define a variable inside
modules.exportsdirectly too.
module.exports.age = 25;- Similarly, we can define a function.
module.exports.addNote = () => {
console.log('addNote');
}Importing npm Modules
- NPM is a package manager that allows you to install and use third-party npm libraries in your code. This opens up a world of possibilities, as there are npm packages for everything.
Initializing npm
- A Node.js application needs to initialize npm before it can be used.
- Run
npm initfrom the root of the project to get that done. That command will ask you a series of questions about the project and it’ll use the information to generate apackage.jsonfile in the root of the project.
{
"name": "notes-app",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
}Installing an npm Module
npm installcommand can be used to install a new module in the project.
# installs version 10.8.0 of validator
npm install [email protected]
# installs the latest version
npm install validator- The command does three important things:
- It creates a
node_modulesdirectory. npm uses this directory to store all the code for the npm modules you have installed. - It adds the module as a dependency by listing it in the dependencies property in
package.json. This allows tracking and managing of installed modules. - npm creates a
package-lock.jsonfile. This includes detailed information about the modules you’ve installed which helps keep things fast and secure.
- It creates a
- You should never make changes to
node_modulesorpackage-lock.json.
# install as a dev dependency only
npm install <package-name> --save-devnode_modulesdirectory shouldn’t be committed to git.
Importing an npm Module
- npm modules can be imported into your script using
require. To load in an npm module, pass the npm module name torequire.
const validator = require('validator')
console.log(validator.isURL('https/mead.io')) // true
console.log(validator.isEmail('gmail.com')) // false- The script above uses
requireto load invalidator. The script then uses theisURLfunction provided byvalidatorto check if a given string contains a valid URL.
Global npm Modules
- You can use npm modules from outside of your scripts by installing them globally.
- npm modules can be installed globally by adding a
-gflag to the installation command. - Not all modules are designed to be installed globally.
# install as a global utility - doesn't add to the project specific package.json
npm install <package-name> --global - A globally installed module is not added as a dependency to your project. That means you won’t see it listed in
package.jsonorpackage-lock.json. You also won’t find its code innode_modules. - Globally installed modules are located in a special directory in your machine which is created and managed by npm.
What is the difference between .js and .mjs files?
- https://stackoverflow.com/questions/57492546/what-is-the-difference-between-js-and-mjs-files.
- Common JS : uses
requireandmodule.exports. - ECMAScript : uses
importandexport.
// package.json
{
// assume .js is using...
"type": "commonjs", // require/module.exports
"type": "module" // import/export
}.cjs: no matter whattypeis defined, we can use CommonJs syntax..mjs: no matter whattypeis defined, we can use ES6 syntax.