Node.JS写入文件–要将内容写入Node.js中的文件,请使用 node fs模块的writeFile() 函数。
// 引入文件系统模块
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.
// 引入文件系统模块
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-写入文件中,我们学习了借助示例将内容写入文件的过程。