Languages
[Edit]
EN

Node.js - create file

3 points
Created by:
Lilly-Grace-Greig
571

In this article, we would like to show you how to create a file in Node.js.

Quick solution:

const fs = require('fs');

const filePath = './file.txt';
const fileDescriptor = fs.openSync(filePath, 'w');

// Hint: do not forget to close file.

 

Practical example

In this example, we use the fs.openSync() method that returns a file descriptor to created empty file.

const fs = require('fs');

const filePath = './file.txt';
const fileDescriptor = fs.openSync(filePath, 'w');

// Hint: do not forget to close file.

Note:

The solution truncates the file if it exists and create new if it doesn't.

Alternative solution

If you don’t need the file, wrap the function call in a fs.closeSync() to close it.

index.js file:

const fs = require('fs');

const filePath = './file.txt';
fs.closeSync(fs.openSync(filePath, 'w'));

Running:

node index.js

Result:

Project structure before:

/app/
 ├── node_modules/
 ├── index.js
 ├── package-lock.json
 └── package.json

 Project structure after:

/app/
 ├── node_modules/
 ├── file.txt
 ├── index.js
 ├── package-lock.json
 └── package.json

Alternative titles

  1. Node.js - create empty file
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join