开始你的第一个node项目

网上有很多关于Node.js如何安装的教程,我这里只是记录一下,免得自己每次再找

一、安装nvm
在终端执行命令 curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.8/install.sh | bash

修改配置文件 ~/.bashrc ,在里面加入以下文字

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

让配置文件生效 source ~/.bashrc

二、安装node.js
nvm ls-remote
nvm install v8.9.1
nvm ls
nvm use xx.xx
三、新建项目
mkdir firstProject
cd firstProject
npm init
四、写项目代码
例如我之前在 Node.js之使用superagent + cheerio 来爬取网页内容 这篇笔记里面写了一段示例代码:

var superagent = require('superagent');
var cheerio = require('cheerio');

var url = "http://xxx.xxx.com";
var cookie = "locale=zh; sessionid=imq23m240knb3421b35j0x8q82nb8z7qb";

var items = [];
superagent.get(url)
    .set("Cookie", cookie)
    .end(function(error, res) {
        if (error) {
            throw error;
        }

        var $ = cheerio.load(res.text);
        $('.admin-table tbody tr').each(function (idx, value){
                $value = $(value);
                $value.find('td').each(function (iddx, book) {
                    if (0 === iddx) {
                        $book = $(book);
                        $items.push($book.find('a').text());
                    }
                });
                
                
        });

        console.log($items);
    });

将上面这段项目代码放到 index.js 里面。(其实项目的入口文件可以不叫 index.js ,可以叫其他任何名字如 app.js 之类的。只不过为了方面,我习惯用 index.js )

五、安装项目所用到的模块
上面的代码中,我用到了 superagent 和 cheerio ,那么在正式运行项目之前,我要先安装这两个模块。

使用命令 npm i superagent cheerio --save 安装需要的模块

六、启动项目
node index.js 就启动了项目

猜你喜欢

转载自blog.csdn.net/li420520/article/details/83758077