Node.js has a huge number of packages created by different developers that you can easily import into your projects using npm.
Basic console commands:
Create a package.json - configuration file that will describe the installed packages, scripts and application information:
npminit-y
Add package:
npminstallpackage-name
Add package only for development:
npminstall-Dpackage-name
Delete package:
npmuninstallpackage-name
Run code
Running codeUse command node + path to file to run it
nodeapp.js
Running code with passing parameters
nodeapp.jshello123
// app.js// The first two parameters always determine the pathsconstpathToNode=process.argv[0]; // path to node.exe on PCconstpathToApp=process.argv[1]; // path to current file// Your agrumentsconstparam1=process.argv[2]; // helloconstparam2=process.argv[3]; // 123
Environment variablesdotenv is needed to load environment variables from .env file
nodeinstalldotenv
// .envTEST="Hello from .env file";
// app.js// Connect dotenv packageconstdotenv=require("dotenv");dotenv.config();console.log(process.env.TEST); // Hello from .env file
Modules
CommonJSModular system created specifically for Node.js
// module.jsconstmessage="Hello Node.js!";constcalcSum= (a, b) => a + b;module.exports= { message, calcSum };
Of course, the future belongs to ES modules. But there are still a number of difficulties associated with compatibility.
Working with paths
Node.js has a built-in path module for working with paths
constpath=require("path");// global variable showing the path to the current folderconsole.log(__dirname);// global variable showing the path to the current fileconsole.log(__filename);// joins all given path segments together (crossplatform)path.join(__dirname,"modules","mod.js");// return object with properties describing a given pathpath.parse("/home/user/project/data.txt");//resolves a sequence/segments of paths into an absolute pathpath.resolve("/modules","mod.js");// return the platform-specific path segment separatorpath.sep; // '/' or '\'path.isAbsolute("modules/mod.js"); // falsepath.isAbsolute("/modules/mod.js"); // truepath.basename("/home/user/project/app.js"); // app.jspath.extname("/home/user/project/app.js"); // .js
Working with files
Node.js has a built-in fs module for working with files
Create/delete folders
constfs=require("fs");constpath=require("path");// create folder "dir" in current directoryfs.mkdir(path.resolve(__dirname,"dir"), (err) => {if (err) throw err;});// // delete folder "dir" from current directoryfs.rmdir(path.resolve(__dirname,"dir"));
Create/read/update/delete files
// Write data to a new file or overwrite an existing filefs.writeFile("file.txt","Hello Node.js!", (error) => {if (error) throw error;});
// Add data to the end of the filefs.appendFile("file.txt","!!!", (error) => {if (error) throw error;});
To ensure that all operations run in sync one by one, you can add Sync to each method name
System info
Node.js has a built-in os module for OS information
constos=require("os");console.log(os.platform()); // identifying the OS platformconsole.log(os.version()); // identifying the kernel versionconsole.log(os.arch()); // info about CPU architectureconsole.log(os.cpus()); // info about each logical CPU core
Events
Node.js allows you to create so-called Event Emmitters, which call special functions (Listeners) when an event is triggered.
constEventEmitter=require("events");constmyEmitter=newEventEmitter();// Create the event called "helloEvent"myEmitter.on("helloEvent", (param) => {console.log(`Hello, ${param}!`);});// Call the event "helloEvent"myEmitter.emit("helloEvent","Node.js");
// delete allmyEmitter.removeAllListeners();// delete only "helloEvent"myEmitter.removeListener("helloEvent");
Streams
The stream module allow you to read stream data in small chunks (64kb by default)
There are 4 types of streams: Readable, Writable, Duplex (R + W) and Transform.
constfs=require("fs");constpath=require("path");// Create readable streamconstrStream=fs.createReadStream(path.resolve(__dirname,"big.txt") //path to data);// First param is event. There are events:// data, open, ready, error, pause, resume, end, close, readablerStream.on("data", (chunk) => {console.log(chunk);});rStream.on("end", () =>console.log("File has been read"));rStream.on("error", (err) =>console.log(err));
constwStream=fs.createWriteStream(path.resolve(__dirname,"data.txt") // path to writable file);for (let i =0; i <10; i++) {wStream.write(`Text line ${i +1} \n`);}wStream.end(); // close stream
HTTP server
Server operations are the main application area fo Node.js
Basic http server
consthttp=require("http");constPORT=process.env.PORT||3000;constserver=http.createServer((req, res) => {// req - object with request data// res - object with response datares.writeHead(200, {"Content-type":"text/html;", });res.end(`<h1>Welcome to Node.js server</h1>`);});server.listen(PORT, () => {console.log("Server is running...");});
After starting the server, you can view it if open http://localhost://3000 on your browser.
For more convenient and fast creation of servers on Node.js uses various frameworks, such as Express.js, Fastify, Koa.js, Nest.js.