前端培训丁鹿学堂:nodeJS入门指南(一)

37 阅读1分钟
认识nodejs

nodejs是一个JavaScript运行环境,以前js只能运行在浏览器,而node让js可以运行在服务器。所以前端学习了node以后,可以进行后端开发。

node的优点

有超强的高并发能力,实现高性能服务器 开发周期短,成本低。

环境搭建

很简单,去nodejs官网下载,就像安装普通软件一下下一步即可。注意:不是nodeJS中文网,那个不是官方的。 打开命令行工具,输入node -v 出现版本号就代表安装成功。

node模块化

在前端开发中可以通过标签引用不同的js,在node 中是遵循并实现了commonJS规范来管理不同js引入。 1.模块导出
1 用exports.xxx 2.用 modules.exports = {xxx,xxx}

function test1(){
    console.log('test1')
}
function test2(){
console.log('test2')
}
exports.test1 = test1;
exports.test2 = test2;

2.模块引入

let modulesA = require('./modules/a')
let modulesB = require('./modules/b')
modulesA.test1() // test1
modulesB() // test2
node模块管理方法2:es6的写法

node最开始的模块化是按照commonJS规范来的,但是我们前端熟悉的模块化是es6的,现在node也支持了。就是写法不一样,哪个熟悉用哪个就好。但是需要自己先配置一下。

  1. npm init 创建package.js 配置文件,添加type配置项
{
  "name": "day01",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

2.模块导出:

function test2(){
    console.log("Testing test2");
}
export default {
test2
}

3.模块引入

import moduleB from './modules/b.js'
moduleB.test2()