{})"; the method of writing files is "writeFile()", the syntax is "writeFile(path ,data,(err)=>{})”."/> {})"; the method of writing files is "writeFile()", the syntax is "writeFile(path ,data,(err)=>{})”.">
Home > Article > Web Front-end > What is the method of reading and writing files in nodejs
In node, the method for reading files is "readFile()", the syntax is "readFile(Path,(error,data)=>{})"; the method for writing files is "writeFile()" ", syntax "writeFile(path,data,(err)=>{})".
The operating environment of this tutorial: windows7 system, nodejs version 12.19.0, DELL G3 computer.
In nodejs, the file system module (fs for short) allows us to access and interact with the file system on our computer.
Using the fs module, we can perform the following operations:
Create files and directories
Modify files and directories
Delete files and directories
Read the contents of files and directories
...
To write a file from a Node.js application, use the writeFile
method.
Syntax: fs.writeFile(path,data,callback:(err)=>void)
##writeFile method accepts at least the following parameters :
fs and
path modules, write the following code in the file:
fs.writeFile('content.txt', 'All work and no play makes Jack a dull boy!', err => { if (err) throw err process.stdout.write('创建成功!') })The above code will create a file named ## A new file of #content.txt
and added the text All work and no play makes Jack a dull boy!
as content. If there are any errors, the callback function will throw that error. Otherwise, it will output to the console that the file was created successfully.
There are other variations, such as:
The module's path is convenient here. Using the
method in the join
module, you can create a file path like this: <pre class="brush:js;toolbar:false;">const filePath = path.join(process.cwd(), &#39;content.txt&#39;)</pre>
First parameter
Returns the current working directory. Now that you have the file path, you can read the file's contents. Write the following code in the file:
fs.readFile(filePath, (error, data) => { if (error) throw error process.stdout.write(data) })readFile
The method accepts at least two parameters:
There are other variations, such as:
The above is the detailed content of What is the method of reading and writing files in nodejs. For more information, please follow other related articles on the PHP Chinese website!