NodeJS require路徑


項目需要用nodejs,感覺nodejs是前端裝逼神器了,是通向全棧工程師的必經之路哇,接下來開始踏上學習nodejs的征程。下面是第一個hello,world的程序。

1、server.js文件,這相當於服務器腳本。

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。這是執行文件,注意require的路徑。

var server=require("./module/server");
server.start();

在項目目錄下用node運行node index.js,然后在瀏覽器中輸入:http://localhost:8888就能看到令人激動的hello,world,同時在node終端里面也能看到Request recieved。第一個程序運行成功。

上面的程序module是文件夾,其中包含server.js文件。index.js是跟module文件夾同級的。

注意require路徑:

  • 相對路徑之當前目錄:./xxx/xxx.js 或 ./xxx/xxx。
  • 相對路徑之上級目錄:../xxx/xxx.js 或 ../xxx/xxx。
  • 絕對路徑:F:/xxx/xxx.js 或 /xxx/xxx.js 或 /xxx/xxx。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM