Writing files with Node.js
Writing a file
The easiest way to write to files in Node.js is to use the fs.writeFile()
API.
const module "node:fs"
fs = var require: NodeJS.Require
(id: string) => any
require('node:fs');
const const content: "Some content!"
content = 'Some content!';
module "node:fs"
fs.function writeFile(path: fs.PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, callback: fs.NoParamCallback): void (+1 overload)
writeFile('/Users/joe/test.txt', const content: "Some content!"
content, err: NodeJS.ErrnoException | null
err => {
if (err: NodeJS.ErrnoException | null
err) {
var console: Console
console.Console.error(message?: any, ...optionalParams: any[]): void (+1 overload)
error(err: NodeJS.ErrnoException
err);
} else {
// file written successfully
}
});
Writing a file synchronously
Alternatively, you can use the synchronous version fs.writeFileSync()
:
const module "node:fs"
fs = var require: NodeJS.Require
(id: string) => any
require('node:fs');
const const content: "Some content!"
content = 'Some content!';
try {
module "node:fs"
fs.function writeFileSync(file: fs.PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options?: fs.WriteFileOptions): void
writeFileSync('/Users/joe/test.txt', const content: "Some content!"
content);
// file written successfully
} catch (var err: unknown
err) {
var console: Console
console.Console.error(message?: any, ...optionalParams: any[]): void (+1 overload)
error(var err: unknown
err);
}
You can also use the promise-based fsPromises.writeFile()
method offered by the fs/promises
module:
const module "node:fs/promises"
fs = var require: NodeJS.Require
(id: string) => any
require('node:fs/promises');
async function function example(): Promise<void>
example() {
try {
const const content: "Some content!"
content = 'Some content!';
await module "node:fs/promises"
fs.function writeFile(file: PathLike | fs.FileHandle, data: string | NodeJS.ArrayBufferView | Iterable<string | NodeJS.ArrayBufferView> | AsyncIterable<string | NodeJS.ArrayBufferView> | Stream, options?: (ObjectEncodingOptions & {
mode?: Mode | undefined;
flag?: OpenMode | undefined;
flush?: boolean | undefined;
} & EventEmitter<T extends EventMap<...> = DefaultEventMap>.Abortable) | BufferEncoding | null): Promise<void>
writeFile('/Users/joe/test.txt', const content: "Some content!"
content);
} catch (function (local var) err: unknown
err) {
var console: Console
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
log(function (local var) err: unknown
err);
}
}
function example(): Promise<void>
example();
By default, this API will replace the contents of the file if it does already exist.
You can modify the default by specifying a flag:
fs.writeFile('/Users/joe/test.txt', content, { flag: string
flag: 'a+' }, err: any
err => {});
The flags you'll likely use are
Flag | Description | File gets created if it doesn't exist |
---|---|---|
r+ | This flag opens the file for reading and writing | ❌ |
w+ | This flag opens the file for reading and writing and it also positions the stream at the beginning of the file | ✅ |
a | This flag opens the file for writing and it also positions the stream at the end of the file | ✅ |
a+ | This flag opens the file for reading and writing and it also positions the stream at the end of the file | ✅ |
- You can find more information about the flags in the fs documentation.
Appending content to a file
Appending to files is handy when you don't want to overwrite a file with new content, but rather add to it.
Examples
A handy method to append content to the end of a file is fs.appendFile()
(and its fs.appendFileSync()
counterpart):
const module "node:fs"
fs = var require: NodeJS.Require
(id: string) => any
require('node:fs');
const const content: "Some content!"
content = 'Some content!';
module "node:fs"
fs.function appendFile(file: fs.PathOrFileDescriptor, data: string | Uint8Array, callback: fs.NoParamCallback): void (+1 overload)
appendFile('file.log', const content: "Some content!"
content, err: NodeJS.ErrnoException | null
err => {
if (err: NodeJS.ErrnoException | null
err) {
var console: Console
console.Console.error(message?: any, ...optionalParams: any[]): void (+1 overload)
error(err: NodeJS.ErrnoException
err);
} else {
// done!
}
});
Example with Promises
Here is a fsPromises.appendFile()
example:
const module "node:fs/promises"
fs = var require: NodeJS.Require
(id: string) => any
require('node:fs/promises');
async function function example(): Promise<void>
example() {
try {
const const content: "Some content!"
content = 'Some content!';
await module "node:fs/promises"
fs.function appendFile(path: PathLike | fs.FileHandle, data: string | Uint8Array, options?: (ObjectEncodingOptions & fs.FlagAndOpenMode & {
flush?: boolean | undefined;
}) | BufferEncoding | null): Promise<void>
appendFile('/Users/joe/test.txt', const content: "Some content!"
content);
} catch (function (local var) err: unknown
err) {
var console: Console
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
log(function (local var) err: unknown
err);
}
}
function example(): Promise<void>
example();