浅谈NodeJS中require路径问题

您所在的位置:网站首页 nodejs怎么更新 浅谈NodeJS中require路径问题

浅谈NodeJS中require路径问题

2023-02-13 23:28| 来源: 网络整理| 查看: 265

项目需要用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。

以上所述就是本文的全部内容了,希望大家能够喜欢。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3