This article will talk about the fs file system module and introduce the file reading and writing operations in node. I hope it will be helpful to everyone!
##What is fs file system module
fs module is a module officially provided by node.js for operating files. Reading and writing operations on files can be achieved through the fs module. [Related tutorial recommendations:nodejs video tutorial, Programming teaching]
For example:const fs = require('fs');
Read the contents of the specified file
test. txt document, and the content inside is:
12341234
// 引入fs模块 const fs = require('fs'); // 读取文件 fs.readFile('./test.txt','utf-8',function(err,data){ console.log(err);// null console.log(data);// 12341234 })
Write content to the specified file
const fs = require('fs'); fs.writeFile('text.txt', '海绵宝宝', 'utf-8', function(err) { console.log(err);// null })
null will be output. Is that right? Does it mean that the writing has been successful?
text.txt file has been generated. Open it and find that the
SpongeBob SquarePants# we just wrote is official. ##. So if we execute the code again and only the written content changes, what will be the result?
fs.writeFile('text.txt', '派大星', 'utf-8', function(err) { console.log(err);// null })
At this time, we open the
text.txt file again and find that the content inside becomes Pat Star
, which means using wirteFile()
will overwrite the original content of the file. At this time, we can also judge whether the file is written successfully based on the value returned by the parameter of the write file callback function: if null is returned, it means the file is written successfully; otherwise, the writing fails.
EndThrough the fs module of
node.js, we can read and write files Come on, this article is my study notes for learning node.js. If there are any shortcomings, I hope the experts can give me advice. For more node-related knowledge, please visit:
The above is the detailed content of An article to talk about the reading and writing operations of node files. For more information, please follow other related articles on the PHP Chinese website!