Certainly! Below is a Node.js script that accomplishes what you're looking for. This script will:
- Open an HTTP server on a specified port (you can change the port number as needed).
- Listen for all incoming HTTP requests.
- Check if the request method is GET.
- Append the full request URL of each GET request to a specified output text file in real-time.
- Accept the output file path as a command-line argument when you run the script.
Step-by-Step Guide
1. Create the Node.js Script
Create a new file called server.js and paste the following code into it:
// Import required modules
const http = require('http');
const fs = require('fs');
const path = require('path');
// Get the output file path from command-line arguments
const outputFilePath = process.argv[2];
if (!outputFilePath) {
console.error('Please provide the output file path as a command-line argument.');
console.error('Usage: node server.js /path/to/output.txt');
process.exit(1);
}
// Resolve the output file path to an absolute path
const resolvedOutputPath = path.resolve(outputFilePath);
// Create an HTTP server
const server = http.createServer((req, res) => {
// Only proceed if the request method is GET
if (req.method === 'GET') {
// Get the full request URL including query parameters
const fullUrl = req.url;
// Append the URL to the output file with a newline
fs.appendFile(resolvedOutputPath, fullUrl + '\n', (err) => {
if (err) {
console.error('Error writing to file:', err);
} else {
console.log('Logged URL:', fullUrl);
}
});
}
// Send a simple response
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Request received\n');
});
// Choose a port to listen on (you can change this if needed)
const port = 3000;
// Start the server
server.listen(port, () => {
console.log(`Server running and listening on port ${port}`);
console.log(`Logging GET request URLs to: ${resolvedOutputPath}`);
});
2. Run the Script
Open your terminal, navigate to the directory containing server.js, and run the script using Node.js. Provide the path to your desired output text file as a command-line argument.
node server.js /path/to/output.txt
Example:
node server.js ./output.txt
This command tells the script to log GET request URLs to output.txt in the current directory.
3. Test the Server
With the server running, you can now send GET requests to it. Open a web browser or use curl to send requests.
Using a Web Browser:
Visit http://your_server_ip:3000/test?param=value in your browser.
Using curl:
curl "http://your_server_ip:3000/test?param=value"
4. Verify the Output
Open the output file specified (output.txt in this example) and you should see the URLs of the GET requests logged.
Example contents of output.txt:
/test?param=value
/another/path?search=query
Explanation of the Script
-
Modules Used:
http: To create the HTTP server.
fs: To handle file system operations like appending to a file.
path: To resolve the absolute path of the output file.
-
Command-Line Argument:
- The script expects the output file path as a command-line argument (
process.argv[2]).
-
Server Creation:
- The server listens on port
3000. You can change this to any port you prefer.
- For each incoming request, it checks if the method is
GET.
-
Logging the URL:
- It captures
req.url, which includes the path and query string.
- Uses
fs.appendFile to append the URL to the specified output file, followed by a newline character.
- Includes error handling in case the file write fails.
-
Response to Client:
- Sends a simple text response
"Request received\n" to acknowledge the request.
Notes
-
Permissions:
- Ensure that the user running the script has write permissions to the specified output file or directory.
-
Port Usage:
- Make sure the port you choose is open and not blocked by any firewall rules on your server.
-
Real-Time Logging:
- The script appends each URL to the file as requests are received, providing real-time logging.
-
Enhancements (Optional):
- Timestamp Logging:
- You can modify the script to include timestamps with each URL logged.
- Logging Additional Details:
- Log headers, IP addresses, or POST data (if method is extended beyond GET).
- Error Handling:
- Improve error handling to cover more edge cases, like invalid output file paths.
Example with Timestamp Logging
If you wish to include timestamps with each logged URL, you can modify the fs.appendFile call as follows:
// Get the current timestamp
const timestamp = new Date().toISOString();
// Append the timestamp and URL to the output file
const logEntry = `[${timestamp}] ${fullUrl}\n`;
fs.appendFile(resolvedOutputPath, logEntry, (err) => {
if (err) {
console.error('Error writing to file:', err);
} else {
console.log('Logged URL:', fullUrl);
}
});
I hope this helps you set up your Node.js server to log GET request URLs for your API testing! Let me know if you have any questions or need further assistance.