Create A File In NodeJS

3 min read

Table of Contents:

Title Image for the Article

Introduction

See the basics of creating a file in NodeJS and getting user input to create the filename and the contents!

https://github.com/cobb208/create_file_nodejs

Event Loop

NodeJS and the engine that powers JavaScript have a unique type of programming because of something called the event loop. While other programming languages work from top to the bottom, JavaScript uses an event loop that can simply run over other code without waiting for a value.

Since JavaScript was originally designed as the scripting language to create dynamic websites, it had a loop that would listen for user input and be able to monitor several actions without getting bogged down on just one. This has translated over to NodeJS (the V8 engine that powers it also powers Chrome).

Instead of just talking about it let us picture it!

const readline = require('readline').createInterface({
	 input: process.stdin,
	 output: process.stdout
});
let fileName = '';
readline.question('What is the filename?, fName => {
     fileName = fName;
});
console.log(fileName);

If you come from another programming language, it would make sense that whatever the user input would be logged by the console. But it is not...

The event loop will but what is happening on the "readline.question" into the event loop and go past it. So the "fileName" variable being set will not be faster than executing the second line of code.

How do we fix it?

This tutorial will take a look at using callback functions to ensure the event loop works down our workflow instead of moving past it.

Is this the only way?

JavaScript has a unique history of how it works. Since so many companies designed so many ways to do so many things (a mouth full I know...) it creates a lot of ways to accomplish the right plan.

The way this tutorial is using allows for Node to just run it as a script. It is a simple implementation and one of the original ways to fix asynchronous code.

The Code

const fs = require('fs');
const readline = require('readline').createInterface({
	 input: process.stdin,
	 output: process.stdout
});
let fileName = '';
let fileContents = '';
readline.question('What is the file name? ', fName => {
	 fileName = fName + '.txt';
	 readline.question('What are the contents? ', fContents => {
	 	fileContents = fContents;
	 	readline.close();
	 	fs.writeFile(fileName, fileContents, err => {
	 		if(err) throw err;
	 		console.log(`${fileName} has been created`);
	 	});
	 });
})

The first two lines are setting up requirements (packages of other code).

"fs" is the filesystem module that allows NodeJS to talk with the operating system for file manipulation.

"readline" is the abstraction layer to use stdin and stdout. If you are familiar with the C++ language these are the names of the IO stream functions to get user input.

We then declare the variable to hold our file's name and then the file's content.

The readline.question() is a method that takes a couple arguments, the first argument is what will be projected to the user on the console and then the second argument is the callback function that is ran once the input is taken.

The Callback Function()

The callback function is what is used to combat the event loop and skipping over our content. The callback will only be executed once the results of the parent function are done. In this case, the variable (we name) is the output of the readline.question.

As we can see we even chain two more callback functions another one by the readline.question and then the fs.writeFile().

Run it!

Save your file and open up a terminal within the same directory.

Run the command in terminal:

node app.js

Recent Articles

Push Weight with Python

Create a simple terminal application that can let you know how much weight you need to put on the ba...

Validate Forms in TypeScript

Relying on HTML to validate your forms is just one step in ensuring visitors enter their information...

Automation with NodeJS

NodeJS can help you automate simple tasks. Being a web developer you can achieve the same goals as o...

Automation with Python

Python can take boring tasks away from you so you can continue to do other things. It is a scripting...

Speed With Cache in WordPress

Most WordPress sites use Apache as their server. Apache has a lot of tools built into it to speed up...

Social Media