Nodejs学习笔记:基础

本文章主要记录Nodejs基础知识点

安装

首先从Node.js官网下载安装包,并添加到环境变量。然后打开命令行,输入 node --version ,可查看版本信息

npm是Node.js的包管理工具(Node.js Package Manager),在Node.js安装时,npm也安装好了

首个Node.js程序

新建一个hello.js文件,输入代码

'use strict';

console.log('Hello, world.');

 然后在文件所在目录下打开命令行,输入命令 node hello.js ,就可以运行该程序

模块

在Node环境中,一个.js文件就称为一个模块(module)

改造一下hello.js,这样就变成了hello模块。要在模块中对外暴露变量(函数也是变量)用: module.exports = variable; 

'use strict';

var s = 'Hello';

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

module.exports = greet; 

然后在main.js中使用hello模块的greet函数。用Node提供require函数,要引入其他模块暴露的变量用: var foo = require('other_module'); 

'use strict';

// 引入hello模块:
var greet = require('./hello');

var s = 'Michael';

greet(s); // Hello, Michael!

这种模块加载机制被称为CommonJS规范。在这个规范下,每个 .js 文件都是一个模块,它们内部各自使用的变量名和函数名都互不冲突

(非原创 侵删 文章来源https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000)

猜你喜欢

转载自www.cnblogs.com/colin220/p/9307621.html