Write to a file using JavaScript

walden systems, java script, javascript, recursive, files, readdirsync, isfile, statsync, file, io, write, string, file operation
a high-level, interpreted programming language that conforms to the ECMAScript specification. It is a language that is also characterized as dynamic, weakly typed, prototype-based and multi-paradigm. Alongside HTML and CSS, JavaScript is one of the three core technologies of the World Wide Web.[9] JavaScript enables interactive web pages and thus is an essential part of web applications. The vast majority of websites use it,[10] and all major web browsers have a dedicated JavaScript engine to execute it.

Sometimes you might need to create a file using JavaScript. There are many ways to accomplish this task and I would like to discuss one of the ways we are using here at Walden Systems, because we believe this is the most straight forward method to create a file and write to it.

Strategy to creating a file and writing to it is straight forward: First, we will need to include the File System module. Finally, we need to write some something to the file and save it using the writeFile( ) method.


Here are the steps:

First thing we include the File System module :

    var fs = require('fs');

Finally, we need to open a file, write something to the file and save it. We will also employ error checking:

    fs.writeFile('newfile.txt', 'Hello content!', function ( err ) 
    {
           if ( err ) 
               throw err;
               console.log('Saved!');
    } ) ;


So the final code is the following:

    var fs = require('fs')

    fs.writeFile('newfile.txt', 'Hello content!', function ( err ) 
    {
           if ( err ) 
               throw err;
               console.log('Saved!');
    } ) ;