Node.JS写入文件–要将内容写入Node.js中的文件,请使用 node fs模块的writeFile() 函数。
Node.js writeFile()函数的语法
nodejs写入文件example.js
// 引入文件系统模块
var fs = require('fs');
var data = "Hello !"
// 将数据写入文件sample.html
fs.writeFile('sample.txt',data,
// 写入文件后调用的回调函数
function(err) {
if (err) throw err;
// 如果没有错误
console.log("Data is written to file successfully.")
});
当以上程序在Terminal中运行时,
arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node nodejs-write-to-file-example.js
Data is written to file successfully.
示例2 –使用指定的编码将内容写入文件
nodejs写入文件示例2.js
// 引入文件系统模块
var fs = require('fs');
var data = "HELLO";
// 将数据写入文件sample.html,指定编码为ASCII
fs.writeFile('sample.txt',data, 'ascii',
// 写入文件后调用的回调函数
function(err) {
if (err) throw err;
// 如果没有错误
console.log("Data is written to file successfully.")
});
当以上程序在Terminal中运行时,
arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node nodejs-write-to-file-example-2.js
Data is written to file successfully.
总结:
在此Node.js教程-节点FS-写入文件中,我们学习了借助示例将内容写入文件的过程。