Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade
JavaScript is a versatile scripting language primarily used for web development. However, it can also be executed in non-browser environments using Node.js, which allows you to run JavaScript on the server-side or directly on your computer via the command line. This article will guide you through setting up Node.js on a Windows environment and executing JavaScript files using the Command Prompt (CMD).
Download Node.js: Visit the Node.js official website and download the Windows installer. Choose the LTS (Long Term Support) version for stability.
Install Node.js: Run the downloaded installer. Follow the installation wizard, ensuring you check the option to add Node.js to your PATH. This allows you to run Node.js from the command line.
Verify Installation: Open CMD and type the following commands to verify that Node.js and npm (Node Package Manager) are installed correctly:
node -v
npm -v
You should see version numbers for both Node.js and npm.
Create a JavaScript File: Use a text editor like Notepad or VSCode to create a new file named example.js
. Add the following simple JavaScript code:
console.log("Hello, World!");
Execute JavaScript via CMD: Navigate to the directory where your example.js
file is located using the cd
command in CMD. Then, execute the JavaScript file using Node.js:
node example.js
You should see the output Hello, World!
displayed in the command prompt.
For more complex scripts, you can use Node.js to execute JavaScript files that perform various operations, such as reading files, making HTTP requests, or interacting with databases. Here's a simple example that reads a file:
Create a File Reader Script: Add the following code to a new file named readFile.js
:
const fs = require('fs');
fs.readFile('sample.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
Create a Sample Text File: Create a file named sample.txt
in the same directory with some sample text.
Execute the Script: Run the script using Node.js:
node readFile.js
This will output the contents of sample.txt
to the console.
By using Node.js, you can execute JavaScript code directly from the command line in a Windows environment. This capability extends the use of JavaScript beyond web browsers and into server-side and desktop applications, making it a powerful tool for developers.