Share through wifi App

Gaya's techtips
4 min readJan 15, 2022

We can access node js applications using ip addresses in the same network. For example when my pc’s ip address 192.168.1.1 then my mobile ip address 192.168.1.2 also both devices are connected to the same router. Then i can connect with my node js app using link like this

http://192.168.1.1:3000(if hosted in port 3000).

Using this concept we can create simple and lightweight applications to share files in the same network. Following tutorial explains the implementation of that application.

Packages to be install

We need to install ejs, body parser , express and express file upload. Here is command,

npm install body-parser ejs express express-fileupload

You need to initialize packages using npm init command before npm install command. I’m not going to explain the npm init command here…

However my package.json file like following

{
"name": "lan-share",
"version": "1.0.0",
"description": "node js share using lan",
"main": "app.js",
"scripts": {
"test": "nodemon app.js"
},
"author": "GA",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.1",
"ejs": "^3.1.6",
"express": "^4.17.2",
"express-fileupload": "^1.2.1"
}
}

Body parser is used to handle http requests json attributes. Ejs is my view engine for frontend. It is an easy to use engine. Express is my backend library and also used to express-file upload to upload files for the server.

Folders and files

Main directory has 3 files named app.js and package.json and package-lock.json. Package and package lock json will generate in npm init and npm install commands. Main directory has 3 folders named views and files and node_modules. Node modules folder also generated in npm init command.files folder is empty folder for store uploaded files.views folder is also used for store ejs files.

There are 2 ejs files named as index.ejs and success.ejs

Let’s see in app.js file

First of all i required all required libraries to app

var express = require('express');
var bodyParser = require('body-parser');
var fileUpload = require('express-fileupload');
var path = require('path');
var fs = require('fs');

Then create express app using following line of code

var app = express();

Then set ejs to view engine and specify views directory to application folder

app.set('views',__dirname+"/views");
app.set('view engine','ejs');

Then set body parser and express file upload to use app

app.use(bodyParser.json());
app.use(fileUpload());

Then set files directory as static directory

app.use('/files',express.static(path.join(__dirname,"files")));

Then handle main get requests from express using following lines of code.Then set file direction as file directory. Because we want to get an array of files in a directory. Then we can add file names using while loop .finally we can render index file with list of files

app.get('/',(req,res)=>{
const dir = fs.opendirSync(__dirname+"/files");
let listing = [];
let entity;
while((entity = dir.readSync()) != null){
if(entity.isFile()){
listing.push(entity.name);
}
}
dir.closeSync();
res.render('index',{list:listing});
})

Then handle the upload function as post method.actually success page shows success messages and error messages also.that code explains how to upload files in express.

app.post('/upload',async (req,res)=>{
if(!req.files){
return res.render('success',{message:'Could not find file'})
}
const file = req.files.myfile;
const path = __dirname+"/files/"+file.name;
file.mv(path,(err)=>{
if(err){
res.render('success',{message:"error when uploading"})
}
res.render('success',{message:"Successfully Uploaded!"})
})
})

Delete request also handle file delete option

app.get('/delete/:item',(req,res)=>{
//delete item
fs.unlink(__dirname+"/files/"+req.params.item,(error)=>{
if(error){
res.render('success',{message:'deletion Failed'});
}else{
res.render('success',{message:'deletion Success'});
}
})
})

Finally we can listen to our application using app.listen code.

app.listen(3000,()=>{
console.log("Server Started!");
})

app.js file

var express = require('express');
var bodyParser = require('body-parser');
var fileUpload = require('express-fileupload');
var path = require('path');
var fs = require('fs');
var app = express();app.set('views',__dirname+"/views");
app.use(bodyParser.json());
app.use(fileUpload());
app.use('/files',express.static(path.join(__dirname,"files")));
app.set('view engine','ejs');
app.get('/',(req,res)=>{
const dir = fs.opendirSync(__dirname+"/files");
let listing = [];
let entity;
while((entity = dir.readSync()) != null){
if(entity.isFile()){
listing.push(entity.name);
}
}
dir.closeSync();
res.render('index',{list:listing});
})
app.post('/upload',async (req,res)=>{
if(!req.files){
return res.render('success',{message:'Could not find file'})
}
const file = req.files.myfile;
const path = __dirname+"/files/"+file.name;
file.mv(path,(err)=>{
if(err){
res.render('success',{message:"error when uploading"})
}
res.render('success',{message:"Successfully Uploaded!"})
})
})
app.get('/delete/:item',(req,res)=>{
//delete item
fs.unlink(__dirname+"/files/"+req.params.item,(error)=>{
if(error){
res.render('success',{message:'deletion Failed'});
}else{
res.render('success',{message:'deletion Success'});
}
})
})
app.listen(3000,()=>{
console.log("Server Started!");
})

Views

Actually there are no special things more than html css. But ejs lines are much important to work with backend

Here is how to create form to upload file

<form class="" action="/upload" enctype="multipart/form-data" method="post">
<input type="file" name="myfile">
<input type="submit" name="submit" value="submit">
</form>

Here is list implement in ejs. This list is sent in backlend when rendering this page.

<% list.forEach(function(item,index){ %>
<div class="content">
<a target="__blank" href="/files/<%= item %>"><%= item %></a><br>
<a href="/delete/<%= item %>">Delete</a>
</div>
<% }) %>

Here is how to show message in ejs this message was send in file upload and delete options.

<div class="content">
<h1><%= message %></h1>
<a href="/">Return</a>
</div>

Final index.ejs file

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Home</title>
<style media="screen">
form{
padding:10px;
margin:10px;
text-align:center;
}
form input[type=file]{
border:1px solid #000000;
padding:5px;
}
form input[type=submit]{
background-color:#555555;
padding:10px;
padding-left:15px;
padding-right:15px;
color:#ffffff;
margin:10px;
border:none;
}
.content a{
text-decoration:none;
color:#ffffff;
margin:10px
}
.content{
background-color:#555555;
text-align:center;
padding:10px;
border-radius:10px;
margin-left:10%;
margin-right:10%
}
</style>
</head>
<body>
<form class="" action="/upload" enctype="multipart/form-data" method="post">
<input type="file" name="myfile">
<input type="submit" name="submit" value="submit">
</form>
<% list.forEach(function(item,index){ %>
<div class="content">
<a target="__blank" href="/files/<%= item %>"><%= item %></a><br>
<a href="/delete/<%= item %>">Delete</a>
</div>
<% }) %>
</body>
</html>

Final success.ejs file

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>status</title>
<style media="screen">
*{
margin:0;
padding:0;
font-family:'Arial'
}
.content{
position:fixed;
top:50%;
left:50%;
transform:translate(-50%,-50%);
text-align:center;
border:1px solid #333333;
padding:20px;
border-radius:10px
}
.content a{
text-decoration:none;
color:#fff;
background-color:#333333;
padding:8px;
margin:20px;
border-radius:10px
}
.content h1{
padding-bottom:10px;
}
</style>
</head>
<body>
<div class="content">
<h1><%= message %></h1>
<a href="/">Return</a>
</div>
</body>
</html>

--

--