Description of the fs. writeFile method in node. js, node. jsfs

Source: Internet
Author: User

Description of the fs. writeFile method in node. js, node. jsfs

Method description:

Write data to a file asynchronously. If the file already exists, the original content will be replaced.

Syntax:

Copy codeThe Code is as follows:
Fs. writeFile (filename, data, [options], [callback (err)])

Because this method belongs to the fs module, we need to introduce the fs module (var fs = require ("fs") before use "))

Receiving parameters:

Filename (String) file name

Data (String | Buffer) the content to be written, which can be String or buffer data.

Options (Object) option array Object, including:

· Optional value of encoding (string). The default value is 'utf8'. When data enables buffer, this value should be ignored.

· Mode (Number) file read and write permissions. The default value is 438.

· Flag (String) Default Value: 'W'

Callback {Function} callback, passing an exception parameter err.

Example:

Copy codeThe Code is as follows:
Fs.writeFile('message.txt ', 'Hello node', function (err ){
If (err) throw err;
Console. log ('It \'s saved! ');
});

Source code:

Copy codeThe Code is as follows:
Fs. writeFile = function (path, data, options, callback ){
Var callback = maybeCallback (arguments [arguments. length-1]);
If (util. isFunction (options) |! Options ){
Options = {encoding: 'utf8', mode: 438/* = 0666 */, flag: 'W '};
} Else if (util. isString (options )){
Options = {encoding: options, mode: 438, flag: 'W '};
} Else if (! Util. isObject (options )){
Throw new TypeError ('bad arguments ');
}
AssertEncoding (options. encoding );
Var flag = options. flag | 'W ';
Fs. open (path, options. flag | 'w', options. mode, function (openErr, fd ){
If (openErr ){
If (callback) callback (openErr );
} Else {
Var buffer = util. isBuffer (data )? Data: new Buffer (''+ data,
Options. encoding | 'utf8 ');
Var position =/a/. test (flag )? Null: 0;
WriteAll (fd, buffer, 0, buffer. length, position, callback );
}
});
};

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.