如何使用Node.js运行用js编写的服务器
我从这里http://nodejs.org/安装了node.js。 在我的Windows8机器。 将示例服务器代码复制到我的server.js文件中
var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/');
然后打开node.js提示符并写入节点c:/node/server.js,但没有任何反应。 我是一个PHP开发人员只是试着手,任何指导方针真的会有所帮助。
您不需要进入node.js提示符,只需使用标准命令promt和write即可
node c:/node/server.js
这也适用:
node c:\node\server.js
然后在你的浏览器中:
http://localhost:1337
Nodejs是一种脚本语言(如Python或Ruby,不像PHP或C ++)。 要运行你的代码,你需要在terminal / shell /命令提示符下input一个命令。 通过这些名称之一在操作系统中查找应用程序快捷方式。
在terminal上运行的命令将会是
node server.js
但是您首先需要在terminal中浏览与文件server.js
相同的文件夹。 使用terminal的语法因操作系统而异,请查阅其文档。
我打开一个文本编辑器,在我的情况下,我使用了Atom。 粘贴这个代码
var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/');
并保存为
helloworld.js
在
c:\xampp\htdocs\myproject
目录。 接下来我打开node.js commamd提示input
cd c:\xampp\htdocs\myproject
下一个
node helloworld.js
接下来我打开我的浏览器,然后input
http://localhost:1337
在那里。
只要从cmd
的JS文件的目录,并写入node jsFile.js
甚至node jsFile
; 两者都可以正常工作。
你试一试
node server
从该目录中的cmd提示符开始