1.CommonJS
node采用CommonJS規(guī)范,使用module.exports導(dǎo)出接口,require引入模塊
//a.js
module.exports = {
a: function(){console.log('你看的到我嗎?')},
b: 'bb',
}
//b.js
var aModule = require('./a.js');
aModule.a();
同理我們創(chuàng)建服務(wù)的時候會用到一些模塊,如http模塊,express等,詳情見node中文網(wǎng)
2.創(chuàng)建launch.json配置文件
{
? ? "version": "0.2.0",
? ? "configurations": [
? ? ? ? ? {
? ? ? ? ? ?"name": "Run server.js",
? ? ? ? ? ?"type": "node",
? ? ? ? ? ?"request": "launch",
? ? ? ? ? ?"program": "${workspaceRoot}/server.js",
? ? ? ? ? ?"stopOnEntry": false,
? ? ? ? ? ?"args": [],
? ? ? ? ? "cwd": "${workspaceRoot}",
? ? ? ? ? "preLaunchTask": null,
? ? ? ? ? "runtimeExecutable": null,
? ? ? ? ? "runtimeArgs": [
? ? ? ? ? ? ? ? ?"--nolazy"
? ? ? ? ? ?],
? ? ? ? ? "env": {
? ? ? ? ? ? ? ? "NODE_ENV": "development"
? ? ? ? ? ? },
? ? ? ? ?"externalConsole": false,
? ? ? ? ? ?"sourceMaps": false,
? ? ? ? ? ?"outDir": null
? ? ? ?}
? ?]
}
創(chuàng)建json文件是為了引入其他模塊時,需要npm install??梢宰孕衝pm init創(chuàng)建package.json
3.創(chuàng)建服務(wù)
創(chuàng)建server.js,
使用npm引入http模塊,使用終端cd到server.js的父級文件夾下輸入 npm install http 安裝http模塊
引入模塊后我們可以創(chuàng)建一個簡單的服務(wù)了

注:使用‘use strict’嚴(yán)格模式,避免各種潛在的bug
輸入node server.js
此時終端中會打印 。‘running 8091’?
在瀏覽器中輸入 http://localhost:8091 就可以看到這個服務(wù)上的數(shù)據(jù) 如圖:

服務(wù)創(chuàng)建完成??