Node.js allows you to write JavaScript code that runs outside of a browser. This code is often saved in .js files that can be executed from the command line. Here are a few ways to save and run a Node.js script:
1. Create a .js File
To save a Node.js script, simply create a new text file with a .js extension. For example:
myScript.js
You can create this in any text editor like Visual Studio Code, Sublime Text, Atom, etc.
2. Add Node.js Code
In the .js file, write your Node.js code. For example:
const msg = 'Hello World';
console.log(msg);
This script logs "Hello World" to the terminal.
3. Save the File
Be sure to save the .js file in your project directory. For example, you may have a scripts folder where you save all your Node.js scripts.
4. Run the Script
To execute the script, open your terminal and navigate to the script directory. Then run:
node myScript.js
It will execute the code in myScript.js. You should see "Hello World" output to the terminal.
5. Export and Import Scripts
You can also export code from one script and import it into another file. For example:
// myFunctions.js
export const greeting = () => {
console.log('Hello');
};
// main.js
import { greeting } from './myFunctions.js';
greeting(); // Logs "Hello"
It allows you to organize your code into reusable modules.
Saving a Node.js script is as simple as creating a .js file and running it with node. This allows you to write and execute JavaScript code outside of the browser!
Top comments (0)