DEV Community

Cover image for How to Save a Node.js Script
Janki Mehta
Janki Mehta

Posted on

11

How to Save a Node.js Script

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
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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');
};
Enter fullscreen mode Exit fullscreen mode
// main.js 
import { greeting } from './myFunctions.js';

greeting(); // Logs "Hello"
Enter fullscreen mode Exit fullscreen mode

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!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

nextjs tutorial video

📺 Youtube Tutorial Series

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay