nodejs fs create file if not exists
To create a file if it doesn't already exist using Node.js, you can follow these steps:
- Import the fs module: The fs module provides an API for interacting with the file system in Node.js. You can import it using the
require
keyword:
const fs = require('fs');
- Use the
fs.existsSync()
method to check if the file exists: TheexistsSync()
method of the fs module is a synchronous method that returnstrue
if the specified path exists, andfalse
otherwise. You can pass the file path as an argument to this method:
const filePath = 'path/to/file.txt';
const fileExists = fs.existsSync(filePath);
- Create the file if it doesn't exist: If the
fileExists
variable isfalse
, you can create the file using thefs.writeFileSync()
method. This method creates a new file with the specified name and content. You can pass the file path and the content as arguments to this method:
if (!fileExists) {
const content = 'This is the content of the file.';
fs.writeFileSync(filePath, content);
}
And that's it! Following these steps will create a file if it doesn't already exist using Node.js.