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);
Related
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();
})
})
})
})
}
})
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.
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");
Trying to pass contents for files I am reading via res.json. I think I am over writing my res function, but I dont see a fix.
app.get('/uploads/', (res, req) => {
dirname = './client/uploads'
fs.readdir(dirname, function(err, filenames) {
console.log(filenames)
if (err) {
console.log(err);
return;
}
filenames.forEach(function(filename) {
if (filename != '.DS_Store'){
fs.readFile(dirname + "/" + filename, 'utf-8', function(err, content) {
res.json({content: content})
if (err) {
//onError(err);
console.log(err)
return;
}
});
}
});
});
})
You mis-matched the arguments of /uploads route handler, req is the first argument
app.get('/uploads/', (req, res) => {
//...
})
I am not able to upload the file using Connect framework. I have refered the link Connect . Below is my code
app.use(connectDomain())
.use(connectRoute(function (router) {
router.post('/upload', function (req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end(JSON.stringify({fields: fields, files: files}));
});
I am getting always the response as below
received upload:
{"fields":{},"files":{}}
example given in formidable module..
var files = [],
fields = [];
form
.on('field', function(field, value) {
console.log(field, value);
fields.push([field, value]);
})
.on('file', function(field, file) {
console.log(field, file);
files.push([field, file]);
})
.on('end', function() {
console.log('-> upload done');
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received fields:\n\n '+util.inspect(fields));
res.write('\n\n');
res.end('received files:\n\n '+util.inspect(files));
});
form.parse(req);