Your first JavaScript file

Introduction

Until recently(if you think that 2009 is recently), we could only run JS code in a web browser. Node is a JavaScript runtime that executes code outside of the browser. We can use the same JS syntax we know and love to write server-side code, instead of relying on other languages like Python or Ruby. You can build Web Servers, Command Line Tools, Native Apps(VSCode is a Node app!), Video Games, Drone Software, and a whole lot more. In this post, I am going to show you how to write your first little Node script which will make you a directory with an HTML, CSS, and JavaScript file in it.

Getting Started

First, you need to check if you have Node installed on your machine. If you don’t know if you have it, just go to the terminal and write:

This will print out the Node.js version which is currently installed. If you see an error and nothing prints, then you don’t have Node installed. In order to install Node, go to the node website and just press the download button. https://nodejs.org/en/ After installing Node, we need to create a JavaScript file. Let’s call this file script.js . In this file, we are going to write our script. Now that we have Node installed and our file created, it’s time to write our script. For this script, we are going to need to know what the process object is and how the fs module works.

How To Run Node Files

In order to run Node files, you just need to write node and then the file name next to it in the terminal. Th file must be in the same folder that you’re in, or you need to reference that full path relative to where you are at the moment.

process & argv

process is an object that’s available which is in the global scope. It provides information about, and control over, the current Node.js process. It has a bunch of methods and properties. For example, we can see our current working directory.

There is a method called process.argv . It returns an array containing the command line arguments passed when the Node.js process was launched. The first element will be the path where the node executable is, and the second will be the path to the JS file being executed. To call this method you need to go to your JS file and console.log() it.

node script.js [ '/usr/local/bin/node', '/Users/ghostman/scripts/script.js' ] 

Any remaining element will be additional command-line arguments. We can pass them as arguments into a script. Not a function, but it’s a similar idea. I can pass in arguments to a script. Here is an example of a little script that prints out the additional command-line arguments:

const args = process.argv.slice(2) -> slice to remove first two items. for(let arg of args)< console.log(`Hello $`) > 
node script.js Batman Superman 
Hello Batman Hello Superman 

This is a fun little script to help you understand how the file and node work together and how they can be used. Now let’s get to the fun part.

Читайте также:  Python plot axis label

fs Module

The fs module enables interacting with the file system. It has hundreds of methods that you can use. Here is a list so you can see how much they are. https://nodejs.org/dist/latest-v14.x/docs/api/fs.html In order for us to use the fs module, we have to require it. We have to save it in a variable.

fs.mkdirSync

This method creates a directory in our current working directory. There is also an fs.mkdir method, but we will be using the synchronous method because it will not execute anything else until this method is completed. Here is an example of our method:

fs.writeFileSync

This method creates files for us. Just like fs.mkdirSync , this method will not let anything else run until it has finished its process.

Источник

1.1 Your first JavaScript file¶

It is a scripting language. You can write programs and run them on any browser by using JavaScript.

info (1): Scripting languages do not need a compiler.

info (2): Compiler is a program that processes statements written in a particular programming language and turns them into machine language.

What is a JavaScript file?¶

A JavaScript file is a simple text file with js extension.

Examples for JavaScript file names:

How to create a JavaScript file?¶

Simply create a new text file, and name it anything you want with js extension. We will create a JavaScript file with the name script.js

Okay, how to run a JavaScript file?¶

First, create an HTML file: JavaScript needs a browser to run. Let’s create a simple HTML file (name it index.html ):

Note (1): Make sure to have index.html and script.js in the same folder/directory.

       

Second, Link JavaScript File Now we need to link the JavaScript we have just created script.js to our newly created index.html .

We can do it by adding a script tag to our index.html .

1- Open script tag before closing body tag in index.html :

2- Add the src attribute to the script tag:

3- Add the name of the JavaScript, we created before, to the src attribute:

5- Our file will be like this:

    Your first JavaScript file 

Third, Add some code to the script.js : Add the following code to the script.js file (and save it):

alert("Hi there, I come from the JavaScript file you have just created"); 

Now open the index.html file in the browser. WOW! A pop-up will show up saying: Hi there, I come from the JavaScript file you have just created. You have successfully written your first JavaScript code, Congratulation!

Well, How does it work?

  1. The web browser reads the HTML file index.html line by line.
  2. When it finds the tag, it loads the file mentioned in the src attribute script.js .
  3. It reads the code in the script.js line by line.
  4. It executes the code alert . The alert shows a pop-up in the browser with the message mentioned enclosed in the quotation marks alert(‘Message’)
  5. It is just as simple as that.
Читайте также:  Генеративные нейронные сети python

info (3): In fact, every browser has a program that can read and execute JavaScript codes. This program is called an engine. In the Chrome web browser, this engine is called V8.

JavaScript code in the HTML file¶

We can include JavaScript code in the HTML file. Let’s edit our index.html :

          

Notice that the src attribute is removed from the script tag. And the alert line is added inside the script tag. Open index.html in the browser and you will get the same result as before.

How does it work?

  1. The web browser reads the HTML file index.html line by line.
  2. When it finds the tag, it loads the code inside the script tag.
  3. It reads that code line by line.
  4. It executes the code alert .

Another way to run JavaScript code¶

Are you being lazy? You do not want to add any script tag to any HTML file. Well!

2- Right-click anywhere on the page, and click on inspect .

3- A new panel will be displayed on the page, select the console tab.

4- You can see blinking cursor below, write your code there:

alert("Hi there, I come from the JavaScript file you have just created"); 

5- Press enter and the pop-up shows up.

6- Great, right?! Now refresh the page. All the code is gone!!

Important: It is useful to test your code in the console. But keep in mind, this code will not be saved. Every time you refresh the page, you will lose everything you have written in the console.

Источник

Your first Javascript File

Hello everybody, and welcome to Hacoder. Today, we are going to create our First Javascript File.

If you have no prior knowledge of Javascript and still haven’t checked out our previous Javascript Tutorials, then click here.

Alright, let’s create our First Javascript File.

Your First Javascript File:-

In this tutorial, we are going to cover:

  • How to embed Javascript code into the HTML webpage.
  • How to reference your JavaScript from a separate file.
  • How to create your first Javascript powered webpage.

Firstly, we have to create a sample HTML webpage.

Save it as index.html or with any name but with a .html extension.

The JavaScript script is inserted either in the HTML page itself or in a separate file. Firstly lets take a look how Javascript is inserted into HTML webpage.

How to Embed Javascript code into HTML webpage:-

To insert a JavaScript script in an HTML page, you use the tag. Don’t forget the closing tag! All the Javascript code is inside the tag.

We can write the tags either in the section or just before the closing of tag.

We can write the Javascript code inside the section like this:

Читайте также:  In your html source

And we can write the Javascript code just before the tag like this:

Save this as index.html and run it on your Web Browser, by just double clicking on the file.

TO INCREASE THE PAGE SPEED OF YOUR WEBPAGE, YOU SHOULD INSERT YOUR JAVASCRIPT CODE JUST BEFORE THE CLOSING OF TAG. THIS WILL LOAD THE JAVASCRIPT CODE AFTER ALL THE CONTENT OF THE WEBPAGE IS LOADED, WHICH WILL INCREASE THE PAGE SPEED.

Reference your JavaScript from a separate file:-

If your script is longer than a few lines, or you need to apply the same code to several pages in your website, then packaging your JavaScript code into a separate file is your best bet.

In fact, having your JavaScript in its own file will give you the advantage of easily maintaining and reusing your scripts.

Источник

First Hello World Program in JavaScript | 2 Ways to add JavaScript to HTML

first javascript program - featured image

In this tutorial post we will be running our first JavaScript program which is a basic Hello World program where we ill simple print Hello World(or any other text) on the browser.

The 2 softwares needed to start of with JavaScript are –

  1. Text Editor : I will be using Visual Studio Code Text Editor which is highly recommended by many specially for Javascript, however you can use any other text editor like Notepad++ or Sublime text etc.
  2. Browser : Of course a browser is needed to load the HTML document and run the JavaScript so I will be using Google Chrome broswer. You can use any browser of your choice as most modern browsers have JavaScript enabled by default.

There are 2 ways to include JavaScript in your HTML Document –

  1. Embedding JavaScript in the same HTML document
  2. Using External JavaScript file and linking it in your HTML document.
1. Embedding JS in HTML document –

As you can see in the code below, we are embedding JS code using the tag of HTML. Usually when the JavaScript code is small it is directly embedded in the HTML document, however, it is not recommended to embed large sized JS code directly in the HTML document as the code becomes un-organized.

default.html file –

      

javascript embedded in html output

2. External JavaScript File –

As you can see below there are 2 file – one the actual HTML document and other a separate external javascript file (demo.js). This demo.js file is linked in the HTML document using the script tag with the use of the attribute src as shown in the code below. When the javascript code is large, it is highly recommended to use a separate external file to keep the HTML doc and the JS code organized.

default.html file –

demo.js file –

document.write("

External file

");

javascript external file linked in html

So thats it for this basic hello world starter program where we simple printed text on the HTML document(not exactly hello world but you get the point right 😛 ). In the upcoming tutorials we will study more on the JS syntax and fundamentals.

Watch it on YouTube

Источник

Оцените статью