EN
Node.js - create file
3
points
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