Home » Programming » Javascript » Javascript Write To File

How to Write to a File Using JavaScript, With Examples

This article will show you how to write to files from JavaScript – both from the web browser and Node.js environments. With examples on how to write, append, update, delete and rename files.

JavaScript code is usually run from one of two environments – within a web browser when viewing a web page or in a Node.js environment which allows JavaScript to be executed outside of a web browser – commonly used for building back-end services and web apps.

Write to a File From the Browser with JavaScript

First, how to do it from the browser. Modern JavaScript includes built-in tools for this. The steps are as follows:

  • Create a file using the JavaScript Blob object to represent the file
  • Create a URL for the new object
  • Provide a link which the user can click to tell the browser to download the Blob object from the URL as a file

The user can then click the link, and they will be presented with the standard save dialog from their web browser, allowing them to save the generated file wherever they wish.

Here’s how the code looks as a re-usable function you can copy and paste to use yourself:

// A global variable should be defined to hold the URL for the file to be downloaded
// This is good practice as if many links are being generated or the link is being regularly updated, you don't want to be creating new variables every time, wasting memory
var textFileUrl = null;

// Function for generating a text file URL containing given text
function generateTextFileUrl(txt) {
    let fileData = new Blob([txt], {type: 'text/plain'});

    // If a file has been previously generated, revoke the existing URL
    if (textFileUrl !== null) {
        window.URL.revokeObjectURL(textFile);
    }

    textFileUrl = window.URL.createObjectURL(fileData);

    // Returns a reference to the global variable holding the URL
    // Again, this is better than generating and returning the URL itself from the function as it will eat memory if the file contents are large or regularly changing
    return textFileUrl;
};

// Generate the file download URL and assign it to the link
// Wait until the page has loaded! Otherwise the download link element will not exist
window.addEventListener("load", function(){
    document.getElementById('downloadLink').href = generateTextFileUrl('Hello world!');
});

You’ll need the following link in your HTML to display a download button:

<!-- Download link - defaults to # which means clicking it does nothing as no file download link has been assigned (yet) -->
<!-- Note the use of the download attribute! It tells the browser to download the file, and what the default file name should be -->
<a id="downloadLink" href="#" download="myFile.txt">Download</a>

This solution does not attempt to emulate clicking on the generated links or any of that nonsense. Browsers will usually block it, and you shouldn’t be trying to sneak downloads past a user without them expressly clicking a link to save the file themselves anyway.

Write to a File From Node.js

If you’re working in a Node.js environment, all of the tools for managing files are available in the built-in fs library.

Reading or writing files takes time and can halt execution. Previously, it was best to use callbacks to perform file operations once a file has been successfully read or written to.

Now, however, Promises provide a standardized approach for asynchronous tasks. So these examples will use Promises instead of callbacks to keep things modern.

Promises are super important when writing modern JavaScript – if you aren’t yet familiar with them, it’s worth taking a day or two to get to know them well.

Here’s how to write a text file from Node.js:

// Import the promise-based version of the fs library
const fs = require('fs').promises;

// Define some text to be written to a file
var textData = "Hello world!";

try {
    // Write text to the given file name
    // await tells JavaScript to wait for the asyncronous function (Promise) to resolve before continuing
    await fs.writeFile('myFile.txt', textData); 
} catch (error) {
    // Output any errors for inspection
    console.log(error);
}

Note the use of a try/catch statement to handle any errors that may occur.

Appending to a File from Node.js

Following on from above, it’s simple to use the fs library to append data to a file:

const fs = require('fs').promises;

try {
    await fs.appendFile('myFile.txt', textData); 
} catch (error) {
    console.log(error);
}

Updating a File

To update a file, you can either append to it using appendFile or overwrite it using writeFile, as outlined above.

Renaming a File

const fs = require('fs').promises;

try {
    await fs.rename('oldFileName.txt', 'newFileName.txt'); 
} catch (error) {
    console.log(error);
}

Deleting a File

The unlink function will delete a file from the disk:

const fs = require('fs').promises;

try {
    await fs.unlink('myFile.txt'); 
} catch (error) {
    console.log(error);
}

 

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment