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:
xxxxxxxxxx
1
const fs = require('fs');
2
β
3
const filePath = './file.txt';
4
const fileDescriptor = fs.openSync(filePath, 'w');
5
β
6
// Hint: do not forget to close file.
In this example, we use the fs.openSync()
method that returns a file descriptor to created empty file.
xxxxxxxxxx
1
const fs = require('fs');
2
β
3
const filePath = './file.txt';
4
const fileDescriptor = fs.openSync(filePath, 'w');
5
β
6
// Hint: do not forget to close file.
Note:
The solution truncates the file if it exists and create new if it doesn't.
If you donβt need the file, wrap the function call in a fs.closeSync()
to close it.
index.js
file:
xxxxxxxxxx
1
const fs = require('fs');
2
β
3
const filePath = './file.txt';
4
fs.closeSync(fs.openSync(filePath, 'w'));
Running:
xxxxxxxxxx
1
node index.js
Result:
Project structure before:
xxxxxxxxxx
1
/app/
2
βββ node_modules/
3
βββ index.js
4
βββ package-lock.json
5
βββ package.json
Project structure after:
xxxxxxxxxx
1
/app/
2
βββ node_modules/
3
βββ file.txt
4
βββ index.js
5
βββ package-lock.json
6
βββ package.json