Writes data to file and automatically create its directories if not exists.
$ npm install write-to-file
const writeToFile = require("write-to-file");
(async () => {
try {
await writeToFile("foo/bar/baz.txt", "Hello World!");
} catch(error) {
console.error(error.message);
}
})();
If foo/bar
directory does not exist, it will be created automatically.
You can pass the character encoding as the third argument. Default to utf8
.
const writeToFile = require("write-to-file");
(async () => {
const buff = Buffer.from("Hello World!");
try {
await writeToFile("foo.txt", buff.toString("hex"), "hex");
} catch(error) {
console.error(error.message);
}
})();
You can also pass an object:
writeToFile("foo.txt", buff.toString("hex"), {
encoding: "hex"
});
By default, if the file already exists, it will be overwritten. For appending data to a file, you may pass the flag
option:
const writeToFile = require("write-to-file");
(async () => {
try {
await writeToFile("foo.txt", "bar", {
flag: "a"
});
} catch(error) {
console.error(error.message);
}
})();
writeToFile(file, data, [options])
file
(String
): The file path to write to.data
(String
|Buffer
): Data to write.options
(OptionalObject
|String
): You may pass the encoding as the third argument. You may also pass an object:encoding
(String
): The character encoding to use, default toutf8
.mode
(Number
): The file permission to set, default to0o666
.flag
(String
): The file system flag, default tow
.createDirMode
(Number
): The directory permission to set when creating the parent directory that does not exist, default to0o777
.
It returns a Promise
which when resolved contains a true
value.
- create-dir: Module to create directory recursively.