• visual code 下的node.js的hello world


    我装好了visual code ,想运行一个node.js 玩玩。也就是运行一个hello world。 

    一:安装node.js : 我google 安装node.js 就引导我到下载页面:https://nodejs.org/en/download

    有 Windows Installer (.msi) 还有Windows Binary (.zip) ,我不喜欢安装器,就下载了.zip ,解压后不知道怎么安装。后来看了B站视频,解压后,要设置解压的目录到path 路径就好。不过我也没这么做,就下载了.msi 版本,然后让他安装设置好。

    要检查安装是否好,可以在终端运行,也可以vs code 的terminal 下:

    node --version 如果显示版本好,就说明安装好了。

    二:一个简单的 node.js


    在visuan code 里,打开一个目录 open folder, 如果没准备好目录,可以这时新建一个目录,比如:nodejs。然后新建一个文件hello.js, 在文件里输入下面代码:

    1. var msg='hello world';
    2. console.log(msg);

    打开visual code 里的terminal ,node hello.js 程序运行如下:

     PS C:\nodeJs> node hello,js
    hello world
    PS C:\nodeJs> 

    这是一个简单在终端显示hello world 的程序

    三:在浏览器里显示hello world

    新建一个文件 server.js ,文件内容如下:

    1. var http = require('http');
    2. http.createServer(function (req, res) {
    3. res.writeHead(200, {'Content-Type': 'text/plain'});
    4. res.end('Hello World!');
    5. }).listen(8080);

    在terminal 运行 node server.js

    在浏览器里输入: 

    http://localhost:8080/

    这个时候在浏览器里显示 Hello World!

    代码也可这样:

    1. const http = require('http');
    2. const hostname = '127.0.0.1';
    3. const port = 3000;
    4. const server = http.createServer((req, res) => {
    5. res.statusCode = 200;
    6. res.setHeader('Content-Type', 'text/plain');
    7. res.end('Hello World');
    8. });
    9. server.listen(port, hostname, () => {
    10. console.log(`Server running at http://${hostname}:${port}/`);
    11. });

    运行时这样:

    PS C:\nodeJs> node app.js   
    Server running at http://127.0.0.1:3000/

    这个提示浏览器输入 http://127.0.0.1:3000/

    运行结果也一样,浏览器显示 Hello World

    本文简单介绍如何开始node.js ,像我这样,好久不弄,马上知道怎么开始。

  • 相关阅读:
    1155:回文三位数
    Java 注解与反射
    DOM—节点操作
    如何通过GDB分析Native Crash
    智慧路灯控制系统设计方案思路及设计原则
    【Linux】-docker配置容器并打包成镜像
    Python02:python代码初体验
    块设备和总线
    【python爬虫笔记】验证码
    【无标题】
  • 原文地址:https://blog.csdn.net/leon_zeng0/article/details/133334963