NodeJS笔记

Node.js

l node.js组成

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-F8WwuvRD-1623162009046)(file:Users/neru/Library/Group%20Containers/UBF8T346G9.Office/TemporaryItems/msohtmlclip/clip_image023.png)]

l Node.js模块化开发

- 模块由exports对象导出,require方法导入

Node.js规定一个JavaScript文件就是一个模块,内部定义变量函数默认情况下外部无法得到

系统核心模块

Node为JavaScript提供了很多服务器级别的API,这些API绝大多数都被包装到了一个具名的核心模块中了。
例如:http、fs、path、url、net、os、readline…
核心模块:先使用require 方法加载才能使用

系统模块fs文件操作

f:file文件,s:system系统,fs:文件操作系统

const fs = require('fs');
fs.readFile('./01.helloworld.js', 'utf8', (err, doc) => {
   
    if(err) {
   
      console.log(err);
    } else {
   
      console.log(doc);
    }
});

callback错误优先

文件路径Path

06-relativeOrAbsolute.js

const fs = require('fs');

fs.readFile('./01-helloworld.js', 'utf8', (err, doc) => {
   
  console.log(err);
  console.log(doc);
})

使用相对路径’./01-helloworld.js’可能会造成出错,当定位到上一级时,运行06文件,会造成在此文件下找不到01文件:

NerudeMacBook-Air:nodeJs neru$ cd ../
NerudeMacBook-Air:WebstormProjects neru$ node ./nodeJS/06-relativeOrAbsolute.js 
[Error: ENOENT: no such file or directory, open './01-helloworld.js'] {
   
 errno: -2,
 code: 'ENOENT',
 syscall: 'open',
 path: './01-helloworld.js'
}
undefined

所以要使用绝对路径:__dirname, ‘01-helloworld.js’)

const fs = require('fs');
const path = require('path');
console.log(__dirname); // /Users/neru/WebstormProjects/nodeJS
console.log(path.join(__dirname, '01-helloworld.js'));
fs.readFile(path.join(__dirname, '01-helloworld.js'), 'utf8', (err, doc) => {
   
  console.log(err);
  console.log(doc);
})
用户自定义模块

- 模块成员导入

a.js导出模块 --> b.js导入a.js模块

  1. exports

    a.js

    const add = (n1, n2) => n1 + n2;
    //导出
    exports.add = add;
    exports.greeting = name => `Hello ${
           name}`;
    exports.readFile = function(path, callback) {
         
        console.log('文件路径:', path);
    }
    

    b.js

    //  导入
    const a = require('./03-module-a.js');
    console.log(a);
    console.log(a.add(10, 20));
    console.log(a.greeting('andy'));
    
    // 终端定位到文件位置
    // 输入 node 03-module-b.js
    // 若输出为 { add: [Function: add] } / 30
    // 则成功
    
    a.readFile('./a.js');
    
    const fs = require('fs');
    fs.readFile('./03-module-a.js', (err, data) => {
         
        if (err) {
         
            console.log(err);
        } else {
         
            console.log(data);
        }
    })
    

    输出:

    {
         
      add: [Function: add],
      greeting: [Function (anonymous)],
      readFile: [Function (anonymous)]
    }
    30
    Hello andy
    文件路径: ./a.js
    <Buffer 63 6f 6e 73 74 20 61 64 64 20 3d 20 28 6e 31 2c 20 6e 32 29 20 3d 3e 20 6e 31 20 2b 20 6e 32 3b 0a 2f 2f e5 af bc e5 87 ba 0a 65 78 70 6f 72 74 73 2e ... 248 more bytes>
    
  2. (优先)module.exports

    方法一:返回一个JSON Object

    a.js

    var person = {
         
        name: 'Andy',
        age: 18,
        sayHello: function(who) {
         
            console.log(who, ', hello i am', this.name);
        }
    }
    module.exports = person;
    

    b.js

    var andy = require('./a.js')
    andy.sayHello('Candy')
    

    输出

    Candy , hello i am Andy
    

    方法二:返回一个函数

    a.js

     var greeting = function(name) {
         
         console.log('hello', name)
     }
     module.exports = greeting
     console.log(module.exports);
    

    b.js

    var g = require('./a.js')
    new g('Candy')
    

    输出

    [Function: greeting]
    hello Candy
    

    方法三:返回一个函数

    a.js

    var greeting = name => `hello ${
           name}`
    module.exports.greeting = greeting
    console.log(module.exports);
    module.exports = {
         
        name: 'candy'
    };
    console.log(module.exports);
    

    b.js

    var a = require('./a.js')
    

    输出

    {
          greeting: [Function: greeting] }
    {
          name: 'candy' }
    

l 第三方模块

- 什么是第三方模块

别人写好的、具有特定功能的、我们能直接使用的模块即第三方模块,由于第三方横块通常都是由多个文件组成并且被放置在一个文件夹中, 所以又名包。

- 第三方模块有两种存在形式:

  • 以js文件的形式存在,提供实现项目具体功能的API接口。
  • 以命令行工具形式存在,辅助项目开发

- 获取第三方模块

  1. https://www.npmjs.com

  2. 命令行:npm install 模块名称(formidable 文件上传)

- 全局安装与本地安装

库文件 – 本地安装

命令行 – 全局安装

nodemon

nodemon是一个命令行工具,用以辅助项目开发

保存即可执行文件,非常方便

- 下载:nom install nodemon -g (-g为全局安装)

如果是mac的,需要在前面加个sudo:sudo npm install nodemon -g

否则会报错:Missing write access to /usr/local/lib/node_modules

- 使用:nodemon命令替代node命令

nodemon ./01-helloworld.js[nodemon] 2.0.7[nodemon] to restart at any time, enter `rs`[nodemon] watching path(s): *.*[nodemon] watching extensions: js,mjs,json[nodemon] starting `node ./01-helloworld.js`hello nodejsfn函数被调用了01234123[nodemon] clean exit - waiting for changes before restart

当对 01-helloworld.js文件进行修改保存后,终端会重新执行文件


                
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值