1、确保node已安装
node -v
npm -v
2、创建项目文件夹
mkdir first-node-app-demo
3、初始化项目
3.1 执行(输入)命令
cd first-node-app-demo
npm init -y
3.2 控制台输出
3.3 查看项目中的package.json文件
3.4 修改package.json文件
{
"name": "my-first-node-app",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node app.js"
},
"dependencies": {}
}
4、创建应用入口 app.js
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('欢迎来到Node.js!');
} else if (req.url === '/test') {
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('欢迎来到测试(test)页面');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('404 Not Found:该页面暂时不存在!');
}
});
const PORT = 3001;
server.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
5、运行(验证)
完成上述步骤之后,对文件进行保存(ctrl+s), 输入命令“npm start" (运行项目),