Node.js is a very popular server-side JavaScript running environment. Its power lies in its simplified I/O operations, including file operations. This article will introduce how to use the file system (fs) module in Node.js to create and delete files.
1. Create files
Creating files using Node.js is very simple. Files can be created using the fs.writeFile() method. This method accepts three parameters: file name, file content and callback function.
The following is a simple example:
const fs = require('fs'); const fileName = 'example.txt'; const fileContent = '这是一个示例文件。'; fs.writeFile(fileName, fileContent, err => { if (err) { console.error(err); return; } console.log(`${fileName} 已创建!`); });
Among them, the fs.writeFile() method is used to create a file, fileName is the file name, and fileContent is the file content. When the file is created, the callback function will be called to output example.txt has been created
.
2. Delete files
The method of deleting files is also very simple. Files can be deleted using the fs.unlink() method. This method accepts two parameters: file name and callback function.
The following is a simple example:
const fs = require('fs'); const fileName = 'example.txt'; fs.unlink(fileName, err => { if (err) { console.error(err); return; } console.log(`${fileName}已删除`); });
In the above code, the fs.unlink() method is used to delete files. fileName is the name of the file to be deleted. When the file is deleted successfully, the callback function will output example.txt deleted
.
Summary
It is very convenient to use Node.js for file operations. The above are two very simple methods for creating and deleting files. These methods are very useful for any developer who needs to perform file operations in Node.js.
The above is the detailed content of nodejs create delete file command. For more information, please follow other related articles on the PHP Chinese website!