[英]Node.js: In-regards to the use of the function fs.writeFile() in Node.js
fs.writeFile('message.txt', 'Hello Node', function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
I have a question regarding the use of the function fs.writeFile()
in Node, and the fact that it prints strings into a textfile. 我对在Node中使用函数
fs.writeFile()
以及将字符串打印到文本文件这一事实有疑问。
At the moment, I have a piece of code that prints the following into console. 目前,我有一段代码将以下内容打印到控制台中。 Instead of the console, I would like to modify the code a bit so it would print into a textfile.
我想稍微修改一下代码,而不是控制台,以便将其打印到文本文件中。
var options = {
host: 'www.google.com',
path: '/'
};
http.get(options, function(response) {
console.log("Status Code: " + response.statusCode);
for(var item in response.headers) {
console.log(item + ": " + response.headers[item]);
}
I would like to replace console.log
with fs.writeFile
, however, the Hello Node
part of the input in fs.writeFile()
is a string. 我想用
fs.writeFile
替换console.log
,但是, fs.writeFile()
输入的Hello Node
部分是一个字符串。 Thus, I am stuck on this part. 因此,我被困在这一部分。
The documentation for fs.writeFile() for Node.js is here: http://nodejs.org/api/fs.html 用于Node.js的fs.writeFile()的文档位于: http ://nodejs.org/api/fs.html
As explained in the documentation, this is how the fs.writeFile function works fs.writeFile(filename, data, [encoding], [callback])
. 如文档中所述,这就是fs.writeFile函数的工作方式
fs.writeFile(filename, data, [encoding], [callback])
。 My question is in regards to the data
input. 我的问题是关于
data
输入的。
I am fairly new to Node.js, therefore I would like to get some feedback on this, and hopefully work the solution out myself with some pointers. 我对Node.js相当陌生,因此我希望对此有所了解,并希望自己通过一些指针解决该问题。
EDIT 1: Do I use String() which then turns my function into a string? 编辑1:我使用String()然后将函数转换为字符串吗? I don't think this is right, but it could be a possibility.
我认为这是不对的,但这是可能的。
This is the code that solved it: 这是解决它的代码:
http.get(options, function(res) {
fs.appendFile('log.txt', "Status Code: " + res.statusCode + "\n");
for(var item in res.headers) {
fs.appendFile('log.txt', item + ": " + res.headers[item] + "\n");
}
}).on('error', function(e) {
console.log("Error: " + e.message);
});
I used fs.appendFile 我用了fs.appendFile
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.