Home  >  Article  >  Web Front-end  >  How to write a file using fs.writeFile() function in Node.js

How to write a file using fs.writeFile() function in Node.js

不言
不言Original
2019-03-07 10:00:186878browse

The fs.writeFile() function of Node.js writes data to a file asynchronously and replaces the file if it already exists. This function can write data from a string or buffer. This article will introduce to you how Node.js uses the fs.writeFile() function to write files.

How to write a file using fs.writeFile() function in Node.js

Let’s first look at the basic syntax of the fs.writeFile() function

 fs.writeFile(filename, data[, options], callback)

If data is a buffer, it is ignored Encoding options. The default encoding is 'utf8', the default file mode is 0666, and the default flag uses 'w' for write mode.

1. path is the file name with path.

2. data is the string or buffer to be written

3. options can be objects like {encoding, mode, flag}.

4. The callback uses a single parameter error and is used to return the error.

Let’s look at specific examples

The code is as follows

Create a JavaScript file (for example: app.js) and add the following content . This script writes the "Hello World!" string to a file named output.txt in the current directory.

var fs = require('fs');

fs.writeFile("output.txt", "Hello World!", function(err) {
    if(err) {
        return console.log(err);
    }
    console.log("File saved successfully!");
});

This article has ended here. For more exciting content, you can pay attention to other related column tutorials on the PHP Chinese website! ! !

The above is the detailed content of How to write a file using fs.writeFile() function in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn