Prerequisites and Setup
- Ensure Node.js and npm are installed on your machine to handle Node applications and manage dependencies.
- Install the IBM Watson SDK and other necessary libraries in your Node.js application. You can achieve this with npm:
npm install ibm-watson@7.0.1
npm install dotenv
Authenticate with IBM Watson
- To securely store your credentials and configuration, use environment variables. Set up a `.env` file in the root directory of your project.
- Example `.env` contents:
NATURAL_LANGUAGE_UNDERSTANDING_APIKEY=your-ibm-watson-nlu-apikey
NATURAL_LANGUAGE_UNDERSTANDING_URL=your-ibm-watson-nlu-url
- Load these environment variables in your application using the
dotenv
library.
require('dotenv').config();
const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
const nlu = new NaturalLanguageUnderstandingV1({
authenticator: new IamAuthenticator({
apikey: process.env.NATURAL_LANGUAGE_UNDERSTANDING_APIKEY,
}),
serviceUrl: process.env.NATURAL_LANGUAGE_UNDERSTANDING_URL,
version: '2020-08-01',
});
Create a Function for Analyzing Text
- Create a function that uses the Watson NLU instance to analyze text. Utilize different features like sentiment, emotions, keywords, etc., by specifying them in the parameters.
function analyzeText(text) {
const analyzeParams = {
text: text,
features: {
keywords: {},
emotion: {},
sentiment: {},
},
};
return nlu.analyze(analyzeParams)
.then(analysisResults => {
console.log('Analysis Results:', JSON.stringify(analysisResults, null, 2));
return analysisResults;
})
.catch(err => {
console.error('Error:', err);
});
}
Example Usage
- Call the previously created function with any text input you wish to analyze. Handle promises to retrieve the analysis results, as Watson's API requests are asynchronous.
- For instance, you could analyze a piece of text within an async function or with promise chaining.
const textToAnalyze = 'IBM Watson is an amazing tool for natural language understanding.';
analyzeText(textToAnalyze)
.then(results => {
console.log('Analyzed data:', results);
});
// Alternatively, within an asynchronous function
async function performAnalysis() {
try {
const analysisResults = await analyzeText(textToAnalyze);
console.log('Analysis Results:', analysisResults);
} catch (error) {
console.error('Error in analysis:', error);
}
}
performAnalysis();
Integrate into Server-Side Application
- For a practical web application, integrate the Watson NLU function into a Node.js server environment, such as an Express.js app.
- Create an endpoint where clients send text data, and your server responds with the analysis.
const express = require('express');
const app = express();
app.use(express.json());
app.post('/analyze', async (req, res) => {
const { text } = req.body;
try {
const analysisResults = await analyzeText(text);
res.json(analysisResults);
} catch (error) {
res.status(500).send('Error analyzing text.');
}
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});