Install the MySQL module first.
node. js is installed by default, the module file is placed in the/usr/local/lib/node_modules directory, in order to manage cheaply, the module is unified installation here.
$ cd /usr/local/lib $ npm install mysql
Program Files Mysql.js
var Client = require(‘/usr/local/lib/node_modules/mysql‘).Client;var client = new Client();client.user = ‘root‘;client.password = ‘‘;console.log(‘Connecting to MySQL...‘);client.query(‘USE tiny_shop‘); //如果MySQL中没有库表,赶紧建。http = require("http");var server = http.createServer(function(request, response) { response.writeHeader(200, {"Content-Type": "text/html"}); client.query(‘SELECT * FROM tags‘, function selectCb(err, results, fields) { if (err) { throw err; } var data = ‘‘; for (var i=0; i<results.length; i++) { var firstResult = results[i]; data += ‘id: ‘ + firstResult[‘id‘]+‘tag: ‘ + firstResult[‘tag‘]; } response.write(data); response.end();
Run
$ node mysql.js
In the browser, input http://localhost:8080, you can display the data in the database.
How node. js reads MySQL data