Why isn't my http.createServer working in NodeJS? - node.js

I need help with my NodeJS code. The program is working but my server is not being created. Any ideas why? The problem is, I suspect my fs.readFile and fs.writeFile are generating errors, but that doesn't make sense because it would log them. Also, is there something wrong with my http.createServer syntax, like a problem with the res.writeHead?
My code is here:
let http = require("http");
let fs = require('fs');
let readline = require("readline");
let rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("Do you have an html file here? y/n ", function(bool) {
if (bool == "y") {
rl.question("What is its name? ", function(file) {
fs.readFile(file, (err, data) => {
if (err) console.log(err);
rl.question("What code to add? ", function(additionalData) {
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data + additionalData);
res.end();
})
fs.writeFile(file, data + additionalData, err => {
if (err) console.log(err);
})
})
})
})
}
else {
rl.question("New file name: ", function(name) {
rl.question("Data: ", function(data) {
fs.writeFile(name, data, err => {
if (err) console.log(err);
})
fs.readFile(name, (err, data) => {
if (err) console.log(err);
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
})
})
})
})
}
})

Related

Requesting file directly with Node JS server returns with nothing

So I am trying to get a node js server to serve a file. Even when I call the file directly in the url (http://localhost:8080/media/file.mp3) it returns no data. When I console.log on the write statement, it returns false, meaning that some or all the of the data isn't being flushed out and sent to the client.
The code:
http.createServer(function(req, res){
res.on('end',()<= {
if (req.url.includes("media")){
res.setHeader('Content-Type','audio/mp3');
res.setHeader('Retry-After', '1');
res.setHeader('method','POST');
res.setHeader('Connection','keep-alive');
res.writeHead(200,{'Content-Type':'audio/mp3'});
console.log("/path_to_file_from_root_to_index"+req.url);
fs.readFile("/path_to_file_from_root_to_index"+req.url,function(err,data){
if (err){
console.log(err);
} else {
res.write(data);
res.end();
}
});
}).listen(8080);
What is being shown in the browser when req.url='/media/file.mp3':
var fs = require('fs'),
http = require('http'),
path = require('path');
http.createServer(function(req, res) {
if (req.url.includes('media')) {
res.writeHead(200, {
'Content-Type': 'audio/mp3'
});
console.log(path.join(__dirname, '/path_to_file_from_root_to_index' + req.url));
fs.readFile(path.join(__dirname, '/path_to_file_from_root_to_index' + req.url), function(err, data) {
if (err) {
console.log(err);
} else {
res.end(data);
}
});
}
}).listen(8080);

Where is my problem coming from not able to load the array on to the page

const server = http.createServer((req, res) => {
const pathName = req.url;
if(pathName === '/' || pathName === '/overview') {
res.end('This is the overview');
} else if (pathName === '/product') {
res.end('This is the product');
} else if (pathName === '/api') {
fs.readFileSync(`${__dirname}/starter/dev-data/data.json`, 'utf-8', (err, data) => {
const productData = JSON.parse(data);
res.writeHead(200, { 'Content-type': 'application/json'})
res.end(data);
});
} else {
res.writeHead(404, {
'Content-type': 'text/html',
'my-own-header': 'hello-world'
});
res.end('<h1>Page not found</h1>');
}
});
server.listen(8000, '127.0.0.1', () => {
console.log('Listening to requests on port 8000');
});
I'm trying to get some data to render onto the page though it's not working. I've included a picture of what my environment looks like.
I think the forward slashes in fs.readFileSync(`${__dirname}/starter/dev-data/data.json, 'utf-8', (err, data) => should be back slashes.

Axios - How to fix - POST URL net::ERR_CONNECTION_RESET

How to fix this error message?
[xhr.js?b50d:178 POST http://localhost:3000/editor/add net::ERR_CONNECTION_RESET][1]
It works and append data, but I get this error message...
My API looks like this:
app.js
app.post('/editor/add', function (req, res) {
let articleData;
let textData;
let article = {
title: req.body.title,
content: req.body.content
}
fs.readFile(urlPath, 'utf8', (err, data) => {
if (err) {
console.log('readfile => ' + err);
} else {
articleData = JSON.parse(data);
articleData[article.title] = article.content;
textData = JSON.stringify(articleData, null, 2);
fs.writeFile(urlPath, textData, 'utf8', (err) => {
if (err) {
console.log('write file => ' + err);
} else {
console.log('Finished writing');
}
});
}
});
});
And my Axios POST method looks like this.
editor.vue
submitEditor: function() {
var self = this;
self.$axios({
headers: {
"Content-Type": "application/json"
},
method: "post",
url: "http://localhost:3000/editor/add",
data: {
title: "test5",
content: self.html
}
})
.then(res => {
console.log(res);
})
.catch(error => {
if (!error.response) {
// network error
this.errorStatus = "Error: Network Error";
} else {
this.errorStatus = error.response.data.message;
}
});
}
I use Vue/cli, I separate my client code and my server code. They are on a separate folder. I put Vue/cli in my client folder, and express.js in my server folder.
Thank you in advance!
Try sending a response from your route:
fs.writeFile(urlPath, textData, 'utf8', (err) => {
if (err) {
console.log('write file => ' + err);
} else {
console.log('Finished writing');
res.json({ msg: 'success' }); // send the client something
}
});

How do I use `fs.readFile` to read an HTML file in Node.js?

I have used fs.readFileSync() to read HTML files and it's working. But I have a problem when I use fs.readFile(). May you please help me to resolve the problem? Any help will be appreciated!
Using fs.readFileSync():
const http = require("http");
const fs = require("fs");
http.createServer((req, res) => {
res.writeHead(200, {
"Content-type": "text/html"
});
const html = fs.readFileSync(__dirname + "/bai55.html", "utf8");
const user = "Node JS";
html = html.replace("{ user }", user);
res.end(html);
}).listen(1337, "127.0.0.1");
Using fs.readFile(). Why can't it read HTML files?
const http = require("http");
const fs = require("fs");
http.createServer((req, res) => {
res.writeHead(200, {
"Content-type": "text/html"
});
const html = fs.readFile(__dirname + "/bai55.html", "utf8");
const user = "Node JS";
html = html.replace("{ user }", user);
res.end(html);
}).listen(1337, "127.0.0.1");
This has to do with a basic concept of Node.js: asynchronous I/O operations. That means that while you are performing I/O, the program can continue its execution. As soon as the data from your file is ready, it will be processed by code in a callback. In other words, the function does not return a value but as its last operation executes the callback passing the data retrieved or an error. This is a common paradigm in Node.js and a common way to handle asynchronous code. The right invocation of fs.readFile() would look like:
fs.readFile(__dirname + "/bai55.html", function (error, html) {
if (error) {
throw error;
}
const user = "Node JS";
html = html.replace("{ user }", user);
res.end(html);
});
Because of readFile use of callback and do not return the data right away.
Look at the node documentation
fs.readFile('/etc/passwd', (err, data) => {
if (err) throw err;
console.log(data);
});
The issue can be resolved by leverlaging Promise
const fs = require('fs');
const http = require("http");
const fsReadFileHtml = (fileName) => {
return new Promise((resolve, reject) => {
fs.readFile(path.join(__dirname, fileName), 'utf8', (error, htmlString) => {
if (!error && htmlString) {
resolve(htmlString);
} else {
reject(error)
}
});
});
}
http.createServer((req, res) => {
fsReadFileHtml('bai55.html')
.then(html => {
res.writeHead(200, {
"Content-type": "text/html"
});
res.end(html.replace("{ user }", "Node JS"));
})
.catch(error => {
res.setHeader('Content-Type', 'text/plain');
res.end(`Error ${error}`);
})
}).listen(1337, "127.0.0.1");

Why there is not output in browser?

Here is my code:
var http = require('http')
http.createServer(function (req, res) {
res.writeHead(200, {
"Content-Type": "json"
});
fs.readdir('.', function (error, files) {
if (error)
res.end(util.format(error))
files.forEach(function (file) {
fs.stat(file, function (erro, stats) {
console.log(JSON.stringify(stats))
res.write(JSON.stringify(stats))
})
})
})
}).listen(3000);
console.log("server is running!")
When i visit http://127.0.0.1:3000/, there is no output, but the console output is:
{"dev":0,"mode":16822,"nlink":1,"uid":0,"gid":0,"rdev":0,"ino":0,"size":0,"atime":"2014-11-20T13:36:19.000Z","mtime":"2014-11-20T13:36:19.000Z","ctime":"2014-11-20T13:31:53.000Z"}
{"dev":0,"mode":33206,"nlink":1,"uid":0,"gid":0,"rdev":0,"ino":0,"size":11,"atime":"2014-11-20T13:56:21.000Z","mtime":"2014-11-20T13:56:21.000Z","ctime":"2014-11-20T13:56:21.000Z"}
{"dev":0,"mode":33206,"nlink":1,"uid":0,"gid":0,"rdev":0,"ino":0,"size":844,"atime":"2014-11-20T14:24:04.000Z","mtime":"2014-11-20T14:24:04.000Z","ctime":"2014-11-20T13:32:19.000Z"}
{"dev":0,"mode":16822,"nlink":1,"uid":0,"gid":0,"rdev":0,"ino":0,"size":0,"atime":"2014-11-20T14:03:56.000Z","mtime":"2014-11-20T14:03:56.000Z","ctime":"2014-11-20T13:56:21.000Z"}
You need to call res.end() when you're done with your res.write calls.
http.createServer(function (req, res) {
res.writeHead(200, {
"Content-Type": "json"
});
fs.readdir('.', function (error, files) {
if (error)
res.end(util.format(error))
var filesLeft = files.length;
files.forEach(function (file) {
fs.stat(file, function (erro, stats) {
console.log(JSON.stringify(stats))
res.write(JSON.stringify(stats))
// Keep track of how many files' fs.stat calls are left
if (--filesLeft === 0) {
res.end();
}
})
})
})
}).listen(3000);

Resources