File Write
To use Node.Js to create a new file and write to it, we're going to use the File System module. So we need to "import" the module into our Js file:
- JavaScript
- // import the file system module
- const fs = require("fs");
Now that we have access to the File System module, we can write our file. The basic syntax is:
- fs.writeFile ( path/fileName, data[, options], callback)
- - path/fileName: the path and file name to be written - entered as a "string"
- - data: the file data to write - this can be a variable or actual text written as a "string"
- - options: these are optional parameters that can be use for file processing - we'll use this when we read a file
- - callback: this is the callback function which could return any error encountered when trying to write the file
So, for example:
- JavaScript
- // import the file system module
- const fs = require("fs");
- // create a new file and add some data
- fs.writeFile ( "message.txt", "Hello from Node.Js", (err) => {
- if (err) {
- console.error('Error writing to file:', err);
- return;
- }
- console.log('File written successfully!');
- if (err) {
- });
We have added a variable (err) to our callback function. If there is an error creating or writing to this file, then the callback function will return the error, which we can display via the err variable. If there is no error and the file is created and written to successfully, then we just log a message indicating a successful process.