Languages
[Edit]
EN

Node.js - create file

0 points
Created by:
Lilly-Grace-Greig
211

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

Quick solution:

const fs = require('fs');
const filePath = './file.txt';

const fd = fs.openSync(filePath, 'w');

 

Practical example

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

const fs = require('fs');
const filePath = './file.txt';

const fd = fs.openSync(filePath, 'w');

Note:

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

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

const fs = require('fs');
const filePath = './file.txt';

fs.closeSync(fs.openSync(filePath, 'w'));

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
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