項(xiàng)目需要用nodejs,感覺nodejs是前端裝逼神器了,是通向全棧工程師的必經(jīng)之路哇,接下來開始踏上學(xué)習(xí)nodejs的征程。下面是第一個hello,world的程序。
1、server.js文件,這相當(dāng)于服務(wù)器腳本。
var http = require("http");function start() {  function onRequest(request, response) {    console.log("Request recieved")    response.writeHead(200, {      "Content-Type": "text/plain"    });    response.write("hello,world");    response.end();  }  http.createServer(onRequest).listen(8888);}exports.start=start;這是最簡單的一個模塊,http是nodejs自帶的模塊,start是自己定義的一個模塊。
2、index.js。這是執(zhí)行文件,注意require的路徑。
var server=require("./module/server");server.start();在項(xiàng)目目錄下用node運(yùn)行node index.js,然后在瀏覽器中輸入:http://localhost:8888就能看到令人激動的hello,world,同時在node終端里面也能看到Request recieved。第一個程序運(yùn)行成功。
上面的程序module是文件夾,其中包含server.js文件。index.js是跟module文件夾同級的。
注意require路徑:
相對路徑之當(dāng)前目錄:./xxx/xxx.js 或 ./xxx/xxx。
相對路徑之上級目錄:../xxx/xxx.js 或 ../xxx/xxx。
絕對路徑:F:/xxx/xxx.js 或 /xxx/xxx.js 或 /xxx/xxx。
以上所述就是本文的全部內(nèi)容了,希望大家能夠喜歡。
新聞熱點(diǎn)
疑難解答