Import Export
To make objects, functions, classes or variables available to the outside world, simply export them and then import them into other project files where necessary.
"Hello, World!" on Node.jsโ
Node.jsยฎ
is a JavaScript environment built on the Chrome V8 engine.
Let's get started with Node.js
just by typing node in the console:
$ node
>
If you don't have it, then download and install it on your computer.
Now let's try to print something:
$ node
> console.log('hello from Node.js')
// After hitting Enter, you get this:
hello from Node.js
undefined
Feel free to experiment with Node.js
using this interface: it is common to test small pieces of code here if it is not practical to put them directly into a file.
It's time to create our Hello Node.js application!
Let's start by creating the index.js
file. With the next command we create the folder myProject
and enter it.
mkdir myProject && cd myProject
Now we create the index.js
file itself
touch index.js
Open your code editor or download and install it. We recommend VS Code.
Open the code editor and add the folder of the project we created to it.
Now open the side menu by clicking this icon.
Copy the following piece of code into it:
// index.js
console.log('hello from Node.js')
To run this file, you must reopen your terminal and navigate to the directory where index.js
is located.
In VS Code
this can be done by clicking on these icons.
And choose the tab TERMINAL
Once you have successfully navigated to the desired location, run the file using the command
node index.js
You will see that this command will produce the same output as before, printing the string directly to the terminal.
Application modularityโ
It's time to move to the next level! Let's create something a little more complex by splitting our source code into multiple JavaScript files for the sake of readability and maintainability.
Project structureโ
Create the following directory structure (with empty files), but don't create package.json
yet, we will generate it automatically in the next step:
โโโ app
| โโโ calc.js
| โโโ index.js
โโโ index.js
โโโ package.json
To create a new file or folder in VS Code
click the corresponding icon as shown in the picture.
package.jsonโ
Every Node.js
project starts by creating a package.json
file. You can think of it as a JSON representation of the application and its dependencies. It contains the name of your application, the author (you), and any dependencies required to run the application. This is your project map.
You can interactively generate the package.json
file with the command
npm init
in the terminal. After running the command, you will be asked to enter some information, such as your application name, version, description, and so on. No need to worry, just press Enter
until you get the generated JSON and the question is is it ok
?. Press Enter one last time and voila: your package.json has been automatically generated and placed in your application folder. If you open this file in your IDE, it looks very similar to the code snippet below.
// package.json
{
"name": "myproject",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
It is good practice to add a startup script to your package.json
package. So add the following line to the scripts
object:
"scripts": {
"start": "node index.js", // this line
"test": "echo \"Error: no test specified\" && exit 1"
}
Once you have done this, you can start the application with the npm start
command.
Importโ
Now let's go back to the first file you created called index.js
. It is recommended to keep this file very compact: only include the application itself (the index.js
file from the / app
subdirectory created earlier). Copy the following code into your index.js
file and save:
// index.js
require('./app/index')
or shorthand for all index.js
files
// index.js
require('./app')
If a specific file is not specified, then the code interpreter looks for the index.js
file and enters it. This is how we simply connected our first file to the project.
Exportโ
Now it's time to start building a real application. Open the index.js
file from the /app
folder to create a very simple example: adding an array of numbers. In this case, the index.js
file will only contain the numbers that we want to add, and the logic that requires the calculations must be placed in a separate module in the calc.js
file.
Paste this code into the index.js
file in the /app
directory.
// app/index.js
const calc = require('./calc')
const numbersToAdd = [3, 4, 10, 2]
const result = calc.sum(numbersToAdd)
console.log(`The result is: ${result}`)
Now paste the actual business logic into the calc.js
file that can be found in the same folder.
// app/calc.js
const sum = arr => {
return arr.reduce((a, b) => a + b, 0)
}
module.exports.sum = sum // export
In this file, we created a sum
function and exported it, made it available in other files in the project.
To check if you did everything right, save these files, open a terminal and type npm start
or node index.js
. If you did everything correctly, you will receive the answer: 19.
If something went wrong, carefully review the log in the console and find the problem based on it.
Totalโ
So we have completed the preparatory course on JavaScript before the course on mobile development.
Problems?โ
Write to Discord chat.
Questions:โ
To make objects, functions, classes or variables available to the outside world, you need to:
- Export them and then import
- Import them and then export
Node.jsยฎ
is:
- Programming language
- JavaScript environment built on the Chrome V8 engine
- Browser
package.json
is:
- JavaScript environment built on the Chrome V8 engine
- JSON representation of the application and its dependencies
- JSON programming language
In order to understand how much you learned this lesson, take the test in the mobile application of our school on this topic or in our telegram bot.
Links:โ
- MDN web doc. ECMAScript 6 Modules: The Future Is Now
- ES6 Modules and How to Use Import and Export in JavaScript
- "require vs ES6 import / export"
Contributors โจโ
Thanks goes to these wonderful people (emoji key):
Dmitriy K. | Dmitriy Vasilev ๐ต | Resoner2005 ๐ ๐จ ๐ | Navernoss ๐ ๐ ๐จ |