Monday , July 26 2021

How to block unproductive websites and increase productivity using JavaScript

Tired of wasting time on various unproductive websites? Why not create a script that helps you limit the time you spend on these websites?

Sound familiar …?

Just another day, scrolling mine Social media feed and watch memes. I found out that 4 hours had passed since I was sitting in the same position and "Doing Nothing". I hated it! I had to do something about it. It came to my mind, why not create some scripts that would help me limit the amount of time I spend on these websites?

Stop browsing your feed and do something xD (source:

How about creating a script that blocks all these sites? The script allows you to use them only on certain dates of the day. It seems legit! Let's do it. 🙂

Yes, I know there are many simple ways to block any website. Just download some plugins for Chrome, or better any software that does this for us. Well, yes, easy enough! Come on, we're developers, we do not do these things! When we need something, we develop scripts for this rather than using some random make-up to do the job … right?

If you want to download the script directly, you can do it from here.

Let's begin!

Unlike my other tutorial articles, you will not need any directory structure or development environment set up for this project. All you need is NodeJS installed on your system and a good text editor. You can create this script using any language of your choice that supports file management. I chose JavaScript because I love it!

I ❤️ JavaScript! (source:

The basic idea

The idea behind this block we are going to do is very simple. There is a file called hosts. We can add the URL of any website and the URL of a website to which we want to redirect the previous site. Something like this:

Now, whenever we try to open Facebook, it will automatically be redirected to (localhost). This will indirectly block the website.

The hosts file I'm talking about is present in C: Windows System32 drivers etc hosts if you use Windows. If you are a Mac or Linux user, the location of that file is: / etc / hosts.

We modify the file …

Before starting the code, let's try to edit the file and see if it works. Note that only the user with administrator rights can edit this file. If you are on Windows, you can right-click on that file and open it as an administrator. If you are using Linux, you can use the sudo command. I'm using nano to open the file, you can use any other editor of your choice.

sudo nano / etc / hosts

After typing this command, you will be asked to enter your password. You can enter it and open your file. Let's try it 🙂

Well, so we added our "to be blocked" website to the hosts file, now let's check if it worked or not. To check it, go to any web browser and go to that site.

Yippee! It worked: 3

Now that we have verified that our concept is correct, we codify the block.

1. Setting the variables

As I said before, there is no need for a large directory structure or development environment. All you need to do is create a JavaScript file (for example, blocker.js) and start coding.

First of all, we have to import fs (file system) Node module through which we will make changes to our hosts file. You can read the complete documentation of fs here.

const fs = require (& # 39; fs & # 39;);

Now, we will need to initialize 3 variables:

  1. file path – To store the path of the hosts file
  2. redirectPath – For the redirection path (here, localhost)
  3. Web sites – Matrix of websites to be blocked

Furthermore, we will create a call variable delay. This variable will store the value of the duration of time (in milliseconds) after which our script will be repeated. Basically the idea is to keep the script always active to check if it is time to block / unblock websites. To keep it running we will use setInterval () method in JavaScript. We can also use while (true) {} to make an infinite cycle.

At this time we are maintaining the time after which the function repeats itself constantly (for example, 10 seconds). But, this script can be made smarter by setting the delay value equal to the time difference between the current time and the current time in which the state of the script (lock / unlock) must be changed. Doing this is much easier than it feels – so I want you (the reader) to do it yourself, and send me an email, I'd like to hear you ?

const filePath = "/ etc / hosts";
const redirectPath = "";
leave website = [ "","" ];
let delay = 10000;

Note* If you're a Windows user, store it in the filePath variable: C: Windows System32 drivers etc hosts

2. The lock function

Now we will create a block function. We call it from the setInterval method to keep it running after every specified time interval.

let blocker = () => {

Now we will fill in the code inside our blocking function.

Internal block: get the current time

First of all you need to get the current time and then check if it's time to block the website or unlock it.

let date = new date ();
let hours = date.getHours ();
if (hours> = 14 && hours <18) {
console.log (& # 39; Time to block websites & # 39;);
} other {
console.log (& # 39; Time to unlock websites & # 39;);

Inside blocker: Inside If – The If condition is true

Now we have to read the hosts file and convert the recovered data into string (the file readFile () the function will return the data of the buffer that must be converted into a string).

After reading the file, we have to check if each website and the redirection path are present in the hosts file or not. If it is present, then we can ignore it. Otherwise, we must add redirectPath websiteURL to it that will be similar to this: www.someRandomWebsite

To implement this, we will use a for loop. The loop will perform the iteration through each URL in the array of Web sites and check if it exists inside the file. To do this, we will use index of () string method. If the value is greater than zero, ie the specified website is present inside the hosts file, we can simply ignore it. Otherwise, if the value is not greater than zero, we must add the redirectPath file and the website URL (separated by the space).

fs.readFile (filePath, (err, data) => {
fileContents = data.toString ();
for (let i = 0; i <websites.length; i ++) {
leave add website = " n" + redirectPath + "" + websites[i];
if (fileContents.indexOf (addWebsite) <0) {
console.log (& # 39; Website not present in the hosts & # 39; file);
fs.appendFile (filePath, addWebsite, (err) => {
if (err) return console.log (err);
console.log (& # 39; File updated successfully & # 39;);
} other {
console.log (& # 39; Website is present & # 39;);

Inside blocker: Inside Else – If the condition is false

If the condition is false, we must check if the websites in the list are present in the hosts file. If they are present, we must eliminate them.

To eliminate, we will use a simple trick. We will read the file line by line. We create an empty string and check if the current line contains any of the websites in the list. If so, we simply ignore it. Otherwise we will add that line to the string we have initialized. After checking the last line, we will simply replace the current contents of the file with this completeContent string.

The code to do it is very simple. Initialize an empty string first (completeString). Then read the file line by line. Follow the steps indicated in the code below. Then replace the contents of the file with completeString variable.

// Initialize the empty string
let completeContent = & # 39; & # 39 ;;
// Read the file line by line
fs.readFileSync (filePath)
.for Each ((row) => {
// Perform the following procedure to update completeContent
// Replace the contents of the file with the `completeContent` variable
fs.writeFile (filePath, completeContent, (err) => {
if (err) {
return console.log (& # 39; Error! & # 39 ;, err);

Now that we have access to each line, we can check if this line contains any website using a flag and a for loop. We set the flag to 1 (or true) and then run a loop to browse the list of websites. If the line contains the current website (we will check it using String.IndexOf (string) method), reset the flag to 0 and interrupt the current loop. Outside the loop we check, if the flag is 1 (or true), we add the current line to the completeContent variable.

Please also notethat if the flag is 1, we also check if the current line is the last one or not. If it is not the last line, we add the current line to the completeContent string together with " N" so that the next line will be added completeContent from a new line (or with a line break). Follow the following code inside forEach () of the previous code block.

let flag = 1;
for (let i = 0; i <websites.length; i ++) {
if (line.indexOf (websites[i])> = 0) { // the line contains the website
flag = 0;
if (flag == 1) {
if (line === & # 39; & # 39;)
completeContent + = line;
completeContent + = line + " n";

3. Execution of the code for the blocking function

Here is the code for the blocking function in case you were confused with the code distributed in section 2:

Now, to continually perform this function, we can move forward while (true) {} like an infinite cycle. Inside it we can give a little bit of time so that it does not occupy the processor continuously.

Or, a better option is to use the setInterval () function. This continues to repeat the block function after a specific time interval. But, setInterval () it will run for the first time after the specified delay. Therefore we will have to call the block function once before the setInterval function.

blocker ();
setInterval (blocker, delay);

4. All done! We check our script

It's time to run our script. To run the script, open the current working directory in a terminal and type the following command:

sudo node blocker.js

If you are a Windows user, you can open the command prompt as an administrator, go to the project directory and then run the command:

node blocker.js

Please note that, for control purposes only, I am blocking Here is the trial run:

5. The final step …

For Mac and Linux

You can schedule the execution of this script every time someone starts the system using crontab. Cron is a time-based work programmer in computerized operating systems such as Unix. You can read more about cron here.

Then we will add our command through which we will execute the script (sudo node blocker.js) in the cron table. Doing this is very simple: open the terminal using Ctrl + Alt + T, then open crontab using sudo crontab -e. This command will open the cron table.

Notethat We have used sudo crontabno crontab. This will allow us to modify the cron table.

Once opened, add this line at the end (replace path-to-script with the path of your project directory):

@reboot node /path-to-script/blocker.js

That's all! This will run your script every time the system reboots.

For Windows

The script can be scheduled to run every time the system also starts in Windows. Here is a great article that explains how to do it.

Where to go from here?

Are you passionate about open source? Do you want to contribute to this project?
I'm starting a new open source project called "Control yourself"that will be a desktop application made using Electron. The features will include:

  • take input from users on which times they want to block which websites
  • track time spent by a user watching social media websites
  • a Tomato timer
  • and a to-do list with a daily productivity report.

Check the repository and add an "interested" comment to the problem you are interested in working on.

Now let me give you the complete code with the appropriate comments that will help you understand the code:

Complete code (blocker.js)

That's all

Did you find the article useful?

Sign up for TheLeanProgrammer to be the first to receive notifications from me for future updates.

Feel free to contact me at any time if you want to discuss something: D

I would be more than happy if you send your comments or suggestions, or if you ask questions. Also, I like to make new friends – so send me an email.

Thank you so much for reading until the end. You can contact me in case you need assistance:
Email: madhavbahl10[at]gmail[dot]com
LinkedIn: /

Source link

Leave a Reply

Your email address will not be published.