728 x 90

Self Writing Program in Node.js

Self Writing Program in Node.js

So in this tutorial, we will write a program that takes the name in command line arguments and writes that name in the same file that we wrote our program in node.js

How cool would it be to write a program that writes itself? I thought the same, though it has no or very rare practical use case, still, I wanted to give it a try.

So in this tutorial, we will write a program that takes the name in command line arguments and writes that name in the same file that we wrote our program in node.js

Step 1 –

Create a file named index.js

Step 2 –

In that file write below code

const fs = require("fs");

var userName = process.argv[2];

var data = `
console.log("${userName}");
`;

fs.appendFile("index.js", data, function(err) {
  if (err) throw err;
  console.log("Saved!");
});

To run above code

node index.js YourName

You will notice that your file is been changed and new line ( console.log(“YourName”) ) is added to your file at the end

Explanation – >

In above code , we first import “fs” module to work with file system

Then we take input from the command line with the help of “process.argv” which returns an array where the element at index 2 is our provided command line argument

Then we create a variable which contains console.log command which contains user provided username. This console.log will be written in our current file.

Then we use the “fs” module to write that data to the current file. ( Note that here we are passing index.js file which is the same file where we are writing our program, hence self-writing program)

This was just an experiment for fun . I hope you liked it.

Akash
EDITOR
PROFILE

Posts Carousel

Leave a Comment

Your email address will not be published. Required fields are marked with *

Latest Posts

Top Authors

Most Commented

Featured Videos