Home > Web Front-end > JS Tutorial > Instructions for using the fs.writeFile method in node.js_node.js

Instructions for using the fs.writeFile method in node.js_node.js

WBOY
Release: 2016-05-16 16:27:17
Original
1605 people have browsed it

Method description:

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

Grammar:

Copy code The code is as follows:

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

Since this method belongs to the fs module, the fs module needs to be introduced before use (var fs= require(“fs”) )

Receive parameters:

filename (String) File name

data (String | Buffer) The content to be written can be string or buffer data.

options (Object) option array object, including:

· encoding (string) Optional value, default 'utf8', when data is buffer, the value should be ignored.

· mode (Number) File read and write permissions, default value 438

·flag (String) Default value ‘w’

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

Example:

Copy code The code is as follows:

fs.writeFile('message.txt', 'Hello Node', function (err) {
if (err) throw err;
console.log('It's saved!');
});

Source code:

Copy code The 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 labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template