English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Exemplo Node.js:vamos usarNode.jspara introduzir conceitos básicos, exemplos de módulos fs, mysql, http, url, análise de json, etc.
A seguir, apresentamos a lista de exemplos do Node.js que abordaremos neste tutorial do Node.js:
Módulo/Tópico | Exemplos |
Básicos |
|
Sistema de Arquivos |
|
MySQL |
|
URL |
|
JSON |
|
HTTP |
|
aqui está um exemplo simplesExemplo Node.jsusado para imprimir mensagens no console
console.log("Olá! Isso é Node.js!")
Calculator.js
// retorna a soma de dois números exports.add = function (a, b) { return a+b; }; // retorna a diferença de dois números exports.subtract = function (a, b) { return a-b; }; // retorna o produto de dois números exports.multiply = function (a, b) { return a*b; };
var calculator = require('./calculator var a =10, b =5; console.log("Addition: ");+calculator.add(a, b)); console.log("Subtraction: ");+calculator.subtract(a, b)); console.log("Multiplication: ");+calculator.multiply(a, b));
readFileExample.js
// Import the file fs module var fs = require('fs'); var data = 'Learn Node FS module'; // The writeFile function with filename, content, and callback fs.writeFile('newfile.txt', data, function(err) { if (err) throw err; console.log('File is created successfully.'); });
Execute the program using the node command in the terminal or command prompt:
Saída do terminal
$ node createFileExample.js File is created successfully.
This file should be created next to the example node.js program with the content 'Learning Node FS module'.
// Importar módulo do sistema de arquivos var fs = require('fs'); // Read the file sample.html fs.readFile('sample.html', // Callback function called when the file reading is completed function(err, data) { if (err) throw err; // The data is a buffer containing the file content console.log(data.toString('utf-8'));8)) });
Execute the program using the node command in the terminal or command prompt:
Saída do terminal
$ node readFileExample.js <html> <body> <h1>Header</h/h1> <p>I have learnt to read a file in Node.js.</p>/p> </body> </html>
Ensure there is a file named 'sample.txt' next to the node.js example program.
// Import the fs module var fs = require('fs'); // Delete the file named 'sample.txt' fs.unlink('sample.txt', function(err) { if (err) throw err; // If there are no errors, the file has been successfully deleted console.log('File deleted!'); });
Execute the program using the node command in the terminal or command prompt:
Saída do terminal
$ node deleteFile.js Arquivo excluído!
O arquivo foi removido com sucesso.
Neste exemplo, escreveremos o conteúdo "Hello!” para o arquivo de texto sample.txt.
// Importar módulo do sistema de arquivos var fs = require('fs'); var data = "Hello !" // Escrever dados no arquivo sample.html fs.writeFile('sample.txt',data, // função de callback chamada após a escrita do arquivo function(err) { if (err) throw err; // Se não houver erros console.log("Os dados são escritos no arquivo com sucesso.") });
Quando o programa acima for executado no Terminal,
saída do programa
arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node nodejs-escrever-para-arquivo-example.js Os dados são escritos no arquivo com sucesso.
// import mysql module var mysql = require('mysql'); // create a connection variable with the required details var con = mysql.createConnection({ host: "localhost", // IP address of the server running mysql user: "arjun", // mysql database username senha: "senha" // corresponding password }); // Connect to the database. con.connect(function(err) { if (err) throw err; console.log("Conectado!"); });
selectFromTable.js Exemplo simples de consulta SELECT FROM MySQL
// Exemplo de consulta SELECT FROM Node.js MySQL // import mysql module var mysql = require('mysql'); // create a connection variable with the required details var con = mysql.createConnection({ host: "localhost", // IP address of the server running mysql user: "arjun", // mysql database username password: "password", // corresponding password database: "studentsDB" // Usa o banco de dados especificado }); // Estabelece conexão com o banco de dados. con.connect(function(err) { if (err) throw err; // Se a conexão for bem-sucedida con.query("SELECT * FROM students", function (err, result, fields) { // Se ocorrer algum erro ao executar a consulta acima, lança erro if (err) throw err; // Se não houver erro, você receberá o resultado console.log(result); }); });
selectFromWhere.js
// import mysql module var mysql = require('mysql'); // create a connection variable with the required details var con = mysql.createConnection({ host: "localhost", // IP address of the server running mysql user: "arjun", // mysql database username password: "password", // corresponding password database: "studentsDB" // Usa o banco de dados especificado }); // Estabelece conexão com o banco de dados. con.connect(function(err) { if (err) throw err; // Se a conexão for bem-sucedida con.query("SELECT * FROM students WHERE marks>90", function (err, result, fields) { // Se ocorrer algum erro ao executar a consulta acima, lança erro if (err) throw err; // Se não houver erro, você receberá o resultado console.log(result); }); });
Abra um terminal na localização do arquivo .js acima e execute o exemplo de programa Node.js MySQL selectFromWhere.js.
AscOrderExample.js
//import mysql module var mysql = require('mysql'); // create a connection variable with the required details var con = mysql.createConnection({ host: "localhost", // IP address of the server running mysql user: "arjun", // mysql database username password: "password", // corresponding password database: "studentsDB" // Usa o banco de dados especificado }); // Estabelece conexão com o banco de dados. con.connect(function(err) { if (err) throw err; // Se a conexão for bem-sucedida con.query("SELECT * FROM students ORDER BY marks", function (err, result, fields) { // Se ocorrer algum erro ao executar a consulta acima, lança erro if (err) throw err; // Se não houver erro, você receberá o resultado console.log(result); }); });
Executar o exemplo de programa Node.js MySQL ORDER BY.
// import mysql module var mysql = require('mysql'); // create a connection variable with the required details var con = mysql.createConnection({ host: "localhost", // IP address of the server running mysql user: "arjun", // mysql database username password: "password", // corresponding password database: "studentsDB" // Usa o banco de dados especificado }); // Estabelece conexão com o banco de dados. con.connect(function(err) { if (err) throw err; // Se a conexão for bem-sucedida con.query("INSERT INTO students (name,rollno,marks) VALUES ('Anisha',12,95)", função function (err, result, fields) { // Se ocorrer algum erro ao executar a consulta acima, lança erro if (err) throw err; // Se não houver erro, você receberá o resultado console.log(result); }); });
Run the Node.js MySQL program in the terminal above.
UpdateRecordsFiltered.js-Update records in MySQL table
// import mysql module var mysql = require('mysql'); // create a connection variable with the required details var con = mysql.createConnection({ host: "localhost", // IP address of the server running mysql user: "arjun", // mysql database username password: "password", // corresponding password database: "studentsDB" // Usa o banco de dados especificado }); // Estabelece conexão com o banco de dados. con.connect(function(err) { if (err) throw err; // Se a conexão for bem-sucedida con.query("UPDATE students SET marks=84 WHERE marks=74" function (err, result, fields) { // Se ocorrer algum erro ao executar a consulta acima, lança erro if (err) throw err; // Se não houver erro, você receberá o resultado console.log(result); }); });
Run the above program in the terminal
Saída do terminal
arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node UpdateRecordsFiltered.js OkPacket { fieldCount: 0, affectedRows: 3, insertId: 0, serverStatus: 34, warningCount: 0, message: '(Rows matched: 3 Changed: 3 Warnings: 0', protocol41: true, changedRows: 3 }
Execute a DELETE FROM query on the specified table when one or more properties on the table are filtered.
// import mysql module var mysql = require('mysql'); // create a connection variable with the required details var con = mysql.createConnection({ host: "localhost", // IP address of the server running mysql user: "arjun", // mysql database username password: "password", // corresponding password database: "studentsDB" // Usa o banco de dados especificado }); // Connect to the database. con.connect(function(err) { if (err) throw err; // Se a conexão for bem-sucedida con.query("DELETE FROM students WHERE rollno>"10" function (err, result, fields) { // Se ocorrer algum erro ao executar a consulta acima, lança erro if (err) throw err; // Se não houver erro, você receberá o resultado console.log(result); }); });
Run deleteRecordsFiltered.js-Saída do terminal
arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node deleteRecordsFiltered.js OkPacket { fieldCount: 0, affectedRows: 6, insertId: 0, serverStatus: 34, warningCount: 0, message: '', protocol41: true, changedRows: 0}
We can use the DOT (.) operator to access records in the result set as arrays and as properties of records.
// Node.js MySQL result object example // import mysql module var mysql = require('mysql'); // create a connection variable with the required details var con = mysql.createConnection({ host: "localhost", // IP address of the server running mysql user: "arjun", // mysql database username password: "password", // corresponding password database: "studentsDB" // Usa o banco de dados especificado }); // Estabelece conexão com o banco de dados. con.connect(function(err) { if (err) throw err; // Se a conexão for bem-sucedida con.query("SELECT * FROM students", function (err, result, fields) { // Se ocorrer algum erro ao executar a consulta acima, lança erro if (err) throw err; // Se não houver erro, você receberá o resultado // Itera todas as linhas do resultado Object.keys(result).forEach(function(key) { var row = result[key]; console.log(row.name) }); }); });
Execute o programa acima usando o nó no terminal
Saída do terminal
arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node selectUseResultObject.js John Arjun Prasanth Adarsh Raja Sai Ross Monica Lee Bruce Sukumar
// Incluir módulo url var url = require('url'); //localhost:8080/index.php?type=page&action=update&id=',5221'; var q = url.parse(address, true); console.log(q.host); //Retorna 'localhost:8080 console.log(q.pathname); //Retorna/index.php //returns '?type=page&action=update&id=',5221" var qdata = q.query; // Retorna um objeto: {Tipo: página, Ação: 'atualizar', id = '5221} console.log(qdata.type); //Retorna "página" console.log(qdata.action); //Retorna "atualizar" console.log(qdata.id); //Retorna " 5221"
Saída do terminal
$ node urlParsingExample.js localhost:8080 /index.php ?type=page&action=update&id=5221 page update 5221
Os seguintes exemplos podem ajudá-lo a usar a função JSON.parse() e acessar elementos do objeto JSON.
// Dado JSON var jsonData = '{"persons":[{"name":"John","city":"New York"},{"name":"Phil","city":"Ohio"}]}'; // Parsing JSON var jsonParsed = JSON.parse(jsonData); // Acessar Elemento console.log(jsonParsed.persons[0].name);
Executar nodejs-parse-Saída do terminal do json.js
arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node nodejs-parse-json.js John
Exemplo Node.js – Um servidor HTTP que prepara respostas com cabeçalhos HTTP e mensagens.
// Importar o módulo http no arquivo var http = require('http'); // Criar um Servidor http.createServer(function (req, res) { // Cabeçalho HTTP // 200-Confirmação da Mensagem // Para usar o conteúdo html na resposta, “ Content-Type”deve ser“ text / html” res.writeHead(200, {'Content-Type': 'text/html'}); res.write('Node.js says hello!'); //Escrever Resposta para o Cliente res.end(); //Fim da Resposta }).listen(9000); //O objeto do servidor está na porta9000 em escuta
Executar Servidor
$ node httpWebServer.js
Abra o navegador e clique no URL “http://127.0.0.1:9000/”,para disparar uma solicitação para nosso servidor web.