1.如何用node运行js?
- 1.打开终端,输入node, 如下图:
运行:输入js代码,按回车键运行;
退出:ctrl+d (ctrl+c两次)
- 2.使用文件 打开vscode(在终端输入code hello.js回车键,即可直接跳转至vscode新建hello.js文件)输入js代码
运行:终端输入 node hello.js
2.初始化nodejs项目
- 1.新建文件夹my-node-app
- 2.进入终端输入 npm init 回车,根据提示往下进行,生成package.json文件 3.用npm中的scripts实现开发任务自动化
-
- package.json 文件中的scripts 添加
"scripts": {
"start": "node ./dist/index.js",
"test": "jest",
"build": "tsc",
"lint": "eslint"
},
- 2. 进入终端输入npm run start
-
- 安装依赖包: npm install xxx(依赖包名称)
-
- package-lock.json文件 npm outdated是否有更新依赖包
黄色代表有最新版本,但不在你的package.json文件可更新范围中
红色代表存在你的package.json文件指定范围内,可放心更新;
npm update 所有红色的包都会更新到最新版
- 使用nodejs编写web服务器
- 1.创建文件index.js
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type','text/plain');
res.end('hello,world');
});
server.listen(port, hostname, () => {
console.log(`服务器运行在 http://${hostname}:${port}/`)
});
-
2.终端窗口,然后输入以下命令:
node index.js
终端中会输出以下内容:
服务器运行在 http://127.0.0.1:3000/ -
3.打开任何首选的 web 浏览器并访问 http://127.0.0.1:3000。如果浏览器显示字符串 hello,world,则表明服务器正在运行。