From the course: Learning Node.js

Unlock the full course today

Join today to access over 23,200 courses taught by industry experts.

Write to a file

Write to a file

- [Instructor] Since we know how to read files and read directories, next, let's move onto writing our own files. As usual, we'll begin by creating a new file, called demo.js and let's bring in the file system. And as you probably guessed, in order to write a file, we're going to access the file system and use the function called writeFile. The first parameter is the name of the file and we'll be writing a JSON file and we'll simply call it data.json. The second parameter, is the actual data that will be written to the file. We could add it inline, but I'm going to create a variable for that. So above our function, let's add a variable called data and set it to a JSON object. Inside here, we'll add a property called name and we'll pass in Bob as the value. And then, let's pass our new data object as the second parameter to our writeFile function. Let's save that, so let's go ahead and execute it. I'll use node and specify demo.js. And as you can see, a data.json file is created. But…

Contents