初学nodejs中涉及到模块导入内容的简单原理(参考廖雪峰的教程)

最近在学习nodejs前端的一些内容,作为一名java程序员还是有点小理想的(全栈全栈-_-!!!),希望自己能坚持住,好了不说废话了,下面我们进入正题…

本人是跟着廖雪峰大神的网站学习的,话说python和git也是在他那里学习的,非常推荐,我使用了他推荐的IDE,VSCode发现用起来还不错挺舒服的。

项目目标:写了简单的两个模块,一个是hello.js模块,一个是main.js模块,我们需要实现在main模块中调用hello模块的方法。
下面我们分别看下hello模块和main模块
hello.js

'use strict';

var name = 'Node.js';
var s = `Hello, ${name}!`;

function greet(name) {
    console.log(s + ',' + name + '!');
}
function greet1(name) {
    console.log(name + '!');
}
function greet2(name) {
    console.log(name + '!');
}

/*
// 准备module对象:
var module = {
    id: 'hello',
    exports: {}
};

这个案例就能说明,只需要将你要对外提供的函数写入module属性exports中即可
1.如果是只有一个函数对象,直接放入即可,
function greet(name) {
    console.log(s + ',' + name + '!');
}
module.exports = greet;
调用模块获取被调用如下代码
var greet = require("./hello");
调用方式:
greet('cronous');
2.如果是多个对象,采用属性赋值的方式
module.exports.attr_name = value;

获取如下

greet.attr_name(参数);
*/
//将模块方法暴露出去,塞入exports属性
module.exports.greet = greet;
module.exports.greet1 = greet1;
module.exports.greet2 = greet2;

main.js

'use strict';
//引入hello模块

var greet = require("./hello");//这个greet就相当于module.exports

var s = 'cronous';
var s1 = 'a';
var s2 = 'b';
greet.greet(s);//分别从exports中拿出函数
greet.greet1(s1);
greet.greet2(s2);

该案例输出:

Hello, Node.js!,cronous!
hello.js:7
a!
hello.js:10
b!

ps:在这个vscode环境的搭建中,我出现了一个低级问题,是复制代码造成的,我这里记下来,为以后学习的人作为参考吧,但我需要调试运行main.js时候出现问题提示:

D:\tools\nodejs\node.exe --nolazy --inspect-brk=6937 hello.js 
Debugger listening on ws://127.0.0.1:6937/3cd6a272-4b27-4cfa-b5f9-cc6b9d1dafc5
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
Waiting for the debugger to disconnect...

最后发现是vscode的运行模块配置问题:我原来的配置代码因为是粘贴的,所以没有修改,如下:

{
    "version": "0.2.0",
    "configurations": [

        {
            "name": "Run demo",
            "type": "node",
            "request": "launch",
            "program": "${workspaceRoot}/hello.js",//这里的入口路径没修改,应该为main.js
            "stopOnEntry": false,
            "args": [],
            "cwd": "${workspaceRoot}",
            "preLaunchTask": null,
            "runtimeExecutable": null,
            "runtimeArgs": [
                "--nolazy"
            ],
            "env": {
                "NODE_ENV": "development"
            },
            "externalConsole": false,
            "sourceMaps": false,
            "outDir": null
        }
    ]
}

修改后问题解决

自己觉得学习中比较有意思的点我就记在博客上,希望自己能坚持下去
文中具体细节内容说明请详见廖雪峰的网站https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/001434502419592fd80bbb0613a42118ccab9435af408fd000

猜你喜欢

转载自blog.csdn.net/cronousgt/article/details/81062530