English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

NodeJS Basic Tutorial

NodeJS Express.js

NodeJS Buffer & URL;

NodeJS MySql

NodeJS MongoDB

NodeJS File (FS)

NodeJS Others

Node.js Write File in FS

Node.JS File Writing–To write content to a file in Node.js, please use node fs modulewriteFile() Function.

Syntax of Node.js writeFile() function

// Import the file system module
var fs = require('fs'); 
 
var data = "Hello !"
 
// Write data to the file sample.html
fs.writeFile('sample.txt', data, 
    // Callback function called after writing to the file
    function(err) {  
        if (err) throw err; 
        // If there is no error
        console.log("Data is written to the file successfully.") 
 });

When the above program is running in the Terminal

arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node nodejs-write-to-file-example.js 
Data is written to the file successfully.

Example2 –Write content to a file using specified encoding

// Import the file system module
var fs = require('fs'); 
 
var data = "HELLO"; 
 
// Write data to the file sample.html, specifying ASCII encoding
fs.writeFile('sample.txt', data, 'ascii', 
    // Callback function called after writing to the file
    function(err) {  
        if (err) throw err; 
        // If there is no error
        console.log("Data is written to the file successfully.") 
 });

When the above program is running in the Terminal

arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node nodejs-write-to-file-example-2.js  
Data is written to the file successfully.

Summary:

In this Node.js tutorial-Node.js File System-In this file writing, we learned the process of writing content to a file with examples.