我今天才真正了解到Node.js,我读了太多的书,这让我头疼。我已经启动并运行了节点服务器。我在节点服务器上还有一个.JS文件,可以写入文本文件。我希望看到只有一个变量(名称)从我的Javascript应用程序传递到运行Node.js的服务器,以便更新日志文件。据我所知,AJAX是实现这一目标的最佳方式。有没有人可以通过一个小的代码示例让我朝着正确的方向前进?
服务器运行节点上的File.js代码
var fs = require('fs'), str = 'some text';
fs.open('H://log.txt', 'a', 666, function( e, id )
{
fs.write( id, str + ',', null, 'utf8', function(){
fs.close(id, function(){
console.log('file is updated');
});});});
发布于 2012-04-27 06:37:22
这就是我将如何做你提到的:
创建一个快速的http服务器,查看任何连接的request变量,获取传入的参数,并将其写入文件。
var http = require('http');
http.createServer(function (req, res) {
var inputText = req.url.substring(1);
processInput ( inputText );
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Completed.');
}).listen(1337, '127.0.0.1');编辑这里:当然,你仍然需要定义什么是processInput。
function processInput ( text )
{
// What you had before
var fs = require('fs');
fs.open ('H://log.txt', 'a', 666, function (e, id )
{
fs.write ( id, text + ',', null, 'utf8', function() {
fs.close(id, function() {
console.log('file is updated');
}
}
});
}这样,当您向
127.0.0.1:1337/写入
它会将单词" write“写入文件(如果processInput写入输入)。
另一种处理方法是在URI中使用参数。关于如何做到这一点的更多信息可以在here at the nodejs api上找到。
祝好运!
https://stackoverflow.com/questions/10340022
复制相似问题